More info when raising an exception

This commit is contained in:
Honza Kral
2013-07-30 14:25:10 +02:00
parent 78f5f0f4bb
commit 0bde2d5317
2 changed files with 34 additions and 8 deletions
+13 -5
View File
@@ -55,6 +55,18 @@ class Connection(object):
status_code or 'N/A', duration, exc_info=exception is not None
)
def _raise_error(self, status_code, raw_data):
error_message = raw_data
additional_info = None
try:
additional_info = json.loads(raw_data)
error_message = additional_info.get('error', error_message)
except:
# we don't care what went wrong
pass
raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
class RequestsHttpConnection(Connection):
def __init__(self, **kwargs):
@@ -78,11 +90,7 @@ class RequestsHttpConnection(Connection):
# raise errors based on http status codes, let the client handle those if needed
if not (200 <= response.status_code < 300):
self.log_request_fail(method, request.url, duration, response.status_code)
if response.status_code in HTTP_EXCEPTIONS:
raise HTTP_EXCEPTIONS[response.status_code](response.text)
raise TransportError(response.text)
self._raise_error(response.status_code, raw_data)
self.log_request_success(method, request.url, request.path_url, body, response.status_code, raw_data, duration)
+21 -3
View File
@@ -9,17 +9,35 @@ class SerializationError(ElastiSearchException):
class TransportError(ElastiSearchException):
pass
""" Exception raised when ES returns a non-OK (>=400) HTTP status code. """
@property
def status_code(self):
""" The HTTP status code of the response that precipitated the error. """
return self.args[0]
@property
def error(self):
""" A string error message. """
return self.args[1]
@property
def info(self):
""" Dict of returned error info from ES, where applicable. """
return self.args[2]
def __str__(self):
return 'TransportError(%d, %r)' % (self.status_code, self.error)
class ConnectionError(TransportError):
pass
""" Error raised when there was an exception while talking to ES. """
class NotFoundError(TransportError):
" 404 "
pass
# more generic mappings from status_code to python exceptions
HTTP_EXCEPTIONS = {
404: NotFoundError,
}