From 04de2fd0eac4d8bedad33b1efcd0c0f1ab093662 Mon Sep 17 00:00:00 2001 From: David Pursehouse Date: Fri, 14 Jun 2013 18:02:20 +0200 Subject: Add handling of HTTP error status codes in responses Change-Id: I9cdb6b7ff2bf6ea20925c5b2eac68ef454a6ea23 --- pygerrit/rest/__init__.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) (limited to 'pygerrit/rest/__init__.py') diff --git a/pygerrit/rest/__init__.py b/pygerrit/rest/__init__.py index 987eaa3..bfa6fac 100644 --- a/pygerrit/rest/__init__.py +++ b/pygerrit/rest/__init__.py @@ -53,13 +53,37 @@ class GerritRestAPIAuthentication(requests.auth.HTTPDigestAuth): return (self.username and self.password) +class GerritRestAPIError(Exception): + + """ Raised when an error occurs during Gerrit REST API access. """ + + def __init__(self, code, message=None): + super(GerritRestAPIError, self).__init__() + self.code = code + self.message = message + + def __str__(self): + if self.message: + return "%d: %s" % (self.code, self.message) + else: + return "%d" % self.code + + def _decode_response(response): """ Decode the `response` received from a REST API call. Strip off Gerrit's magic prefix if it is there, and return decoded JSON content or raw text if it cannot be decoded as JSON. + Raise GerritRestAPIError if the response contains an HTTP error status + code. + """ + try: + response.raise_for_status() + except requests.exceptions.HTTPError as e: + raise GerritRestAPIError(response.status_code, str(e)) + content = response.content if content.startswith(GERRIT_MAGIC_JSON_PREFIX): content = content[len(GERRIT_MAGIC_JSON_PREFIX):] -- cgit v1.2.1