From 07c601eefb0059a516c3f28e39df2e846e681358 Mon Sep 17 00:00:00 2001
From: Pierre Chanial <pierre.chanial@apc.in2p3.fr>
Date: Wed, 2 Feb 2022 12:16:52 +0100
Subject: [PATCH] Improve error handling of ESAP-DB server responses.

---
 esap_client/helpers.py            | 10 ++++++++--
 esap_client/models/collections.py |  4 ++--
 2 files changed, 10 insertions(+), 4 deletions(-)

diff --git a/esap_client/helpers.py b/esap_client/helpers.py
index 57d3aeb..bc99d4e 100644
--- a/esap_client/helpers.py
+++ b/esap_client/helpers.py
@@ -1,5 +1,6 @@
 """This module provides helper functions for the ESAP client."""
-from typing import Type
+import json
+from typing import Any, Type
 
 from requests import Response
 from tabulate import tabulate
@@ -18,7 +19,12 @@ def raise_for_status(response: Response) -> None:
     else:
         cls = ESAPServerError
 
-    error = response.json()
+    error: Any
+    try:
+        error = response.json()
+    except json.JSONDecodeError:
+        error = response.text
+
     if isinstance(error, dict) and 'detail' in error:
         error = error['detail']
     raise cls(f'HTTP Error {response.status_code}: {error}')
diff --git a/esap_client/models/collections.py b/esap_client/models/collections.py
index 66057ce..3901fc4 100644
--- a/esap_client/models/collections.py
+++ b/esap_client/models/collections.py
@@ -19,7 +19,7 @@ def __init__(self, api: str, resource_cls: Type[T]) -> None:
         """The `ResourceCollection` constructor."""
         self.session = BasedSession(api)
         self.deserialize: Callable[[dict], T] = resource_cls.deserialize
-        self.resource_type = type(resource_cls).__name__
+        self.resource_type = resource_cls.__name__.lower()
 
     def __iter__(self) -> Iterator[T]:
         """Iterates through the resources in the collection."""
@@ -32,7 +32,7 @@ def __getitem__(self, key: str) -> T:
         response = self.session.get(f'/{key}')
         if response.status_code == 404:
             raise KeyError(f'Unknown {self.resource_type}: {key}')
-            raise_for_status(response)
+        raise_for_status(response)
         return self.deserialize(response.json())
 
     def __repr__(self) -> str:
-- 
GitLab