diff --git a/ceilometerclient/exc.py b/ceilometerclient/exc.py index 3db1c0cf..8d560389 100644 --- a/ceilometerclient/exc.py +++ b/ceilometerclient/exc.py @@ -43,15 +43,21 @@ class HTTPException(BaseException): self.details = details def __str__(self): - try: - data = json.loads(self.details) - message = data.get("error_message", {}).get("faultstring") + message = "" + if self.details: + message = self.details + try: + data = json.loads(self.details) + message = data.get("error_message", "") + if isinstance(message, dict) and "faultstring" in message: + message = "ERROR %s" % message["faultstring"] + except (ValueError, TypeError, AttributeError): + pass + if message: - return "%s (HTTP %s) ERROR %s" % ( - self.__class__.__name__, self.code, message) - except (ValueError, TypeError, AttributeError): - pass - return "%s (HTTP %s)" % (self.__class__.__name__, self.code) + message = " %s" % message + return "%s (HTTP %s)%s" % (self.__class__.__name__, self.code, + message) class HTTPMultipleChoices(HTTPException): @@ -129,5 +135,10 @@ def from_response(response, details=None): # it is something unexpected raise TypeError("Function 'from_response' expects only response object" " from httplib or requests libraries.") - cls = _code_map.get(code, HTTPException) - return cls(details) + cls = _code_map.get(code) + if cls is None: + exc = HTTPException(details) + exc.code = code + return exc + else: + return cls(details) diff --git a/ceilometerclient/tests/unit/test_exc.py b/ceilometerclient/tests/unit/test_exc.py index b0fd1b14..e67cfc8c 100644 --- a/ceilometerclient/tests/unit/test_exc.py +++ b/ceilometerclient/tests/unit/test_exc.py @@ -41,7 +41,7 @@ class HTTPExceptionsTest(utils.BaseTestCase): def test_str_no_json(self): for k, v in HTTPEXCEPTIONS.items(): exception = v(details="foo") - ret_str = k + " (HTTP " + str(exception.code) + ")" + ret_str = k + " (HTTP " + str(exception.code) + ") foo" self.assertEqual(ret_str, str(exception)) def test_str_no_error_message(self): @@ -54,13 +54,14 @@ class HTTPExceptionsTest(utils.BaseTestCase): for k, v in HTTPEXCEPTIONS.items(): exception = v( details=json.dumps({"error_message": {"foo": "bar"}})) - ret_str = k + " (HTTP " + str(exception.code) + ")" + ret_str = (k + " (HTTP " + str(exception.code) + ") " + + str({u'foo': u'bar'})) self.assertEqual(ret_str, str(exception)) def test_str_error_message_unknown_format(self): for k, v in HTTPEXCEPTIONS.items(): exception = v(details=json.dumps({"error_message": "oops"})) - ret_str = k + " (HTTP " + str(exception.code) + ")" + ret_str = k + " (HTTP " + str(exception.code) + ") oops" self.assertEqual(ret_str, str(exception)) def test_str_faultstring(self):