From cf259c887b0be65be4fa24519de6568aa47654db Mon Sep 17 00:00:00 2001 From: Jan Kaluza Date: May 29 2018 13:30:45 +0000 Subject: Handle also JSON error objects in LightblueSystemError Exception class. --- diff --git a/freshmaker/lightblue.py b/freshmaker/lightblue.py index 3c75f36..22fa36b 100644 --- a/freshmaker/lightblue.py +++ b/freshmaker/lightblue.py @@ -72,14 +72,31 @@ class LightBlueSystemError(LightBlueError): """LightBlue system error""" def _get_error_message(self): - # Remove all newlines if there is + # Try getting the error code from JSON if returned. + try: + msg = "" + json_data = json.loads(self.raw) + if "errors" in json_data: + for error in json_data["errors"]: + if "msg" not in error or "errorCode" not in error: + continue + msg += error["errorCode"] + ": " + error["msg"] + "\n" + if msg: + return msg + except ValueError as e: + log.exception(e) + # If no JSON is returned, try to get the title of HTML page. buf = six.StringIO(self.raw) html = ''.join((line.strip('\n') for line in buf)) match = re.search('(.+)', html) return match.groups()[0] def __str__(self): - return self._get_error_message() + try: + return self._get_error_message() + except Exception as e: + log.exception(e) + raise class LightBlueRequestError(LightBlueError): diff --git a/tests/test_lightblue.py b/tests/test_lightblue.py index 01e8320..08037af 100644 --- a/tests/test_lightblue.py +++ b/tests/test_lightblue.py @@ -109,6 +109,22 @@ description JBWEB000121: This request requires HTTP authentication. def test_raw(self): self.assertEqual(self.fake_error_data, self.e.raw) + def test_str_from_json(self): + content = ( + '{"status":"ERROR","modifiedCount":0,"matchCount":0,' + '"hostname":"periwinklec9.web.prod.int.phx2.redhat.com",' + '"errors":[{"objectType":"error","context":"rest/FindCommand/' + 'containerImage/find(containerImage:null)/containerImage/' + 'includes_multiple_content_streams","errorCode":"' + 'metadata:InvalidFieldReference","msg":' + '"includes_multiple_content_streams in ' + 'includes_multiple_content_streams"}]}') + e = LightBlueSystemError( + http_client.BAD_REQUEST, content) + self.assertEqual( + 'metadata:InvalidFieldReference: includes_multiple_content_streams' + ' in includes_multiple_content_streams\n', str(e)) + def test__str__(self): self.assertEqual( 'JBWEB000065: HTTP Status 401 - JBWEB000009: No client certificate'