From 0bde2d531762982cb76bca3e979cf7836c6b3a11 Mon Sep 17 00:00:00 2001 From: Honza Kral Date: Tue, 30 Jul 2013 14:25:10 +0200 Subject: [PATCH] More info when raising an exception --- elasticsearch/connection.py | 18 +++++++++++++----- elasticsearch/exceptions.py | 24 +++++++++++++++++++++--- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/elasticsearch/connection.py b/elasticsearch/connection.py index e62b91f2..19a904d2 100644 --- a/elasticsearch/connection.py +++ b/elasticsearch/connection.py @@ -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) diff --git a/elasticsearch/exceptions.py b/elasticsearch/exceptions.py index b841d8c2..d032f676 100644 --- a/elasticsearch/exceptions.py +++ b/elasticsearch/exceptions.py @@ -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, }