| 1 |
# coding: utf-8 |
| 2 |
|
| 3 |
# Copyright 2019 IBM All Rights Reserved. |
| 4 |
# |
| 5 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 |
# you may not use this file except in compliance with the License. |
| 7 |
# You may obtain a copy of the License at |
| 8 |
# |
| 9 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
# |
| 11 |
# Unless required by applicable law or agreed to in writing, software |
| 12 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 |
# See the License for the specific language governing permissions and |
| 15 |
# limitations under the License. |
| 16 |
|
| 17 |
import warnings |
| 18 |
from http import HTTPStatus |
| 19 |
from typing import Optional |
| 20 |
|
| 21 |
from requests import Response |
| 22 |
|
| 23 |
|
| 24 |
class ApiException(Exception): |
| 25 |
"""Custom exception class for errors returned from operations. |
| 26 |
|
| 27 |
Args: |
| 28 |
code: HTTP status code of the error response. |
| 29 |
message: The error response body. Defaults to None. |
| 30 |
http_response: The HTTP response of the failed request. Defaults to None. |
| 31 |
|
| 32 |
Attributes: |
| 33 |
code (int): HTTP status code of the error response. |
| 34 |
message (str): The error response body. |
| 35 |
http_response (requests.Response): The HTTP response of the failed request. |
| 36 |
global_transaction_id (str, optional): Globally unique id the service endpoint has given a transaction. |
| 37 |
""" |
| 38 |
|
| 39 |
def __init__(self, code: int, *, message: Optional[str] = None, http_response: Optional[Response] = None) -> None: |
| 40 |
# Call the base class constructor with the parameters it needs |
| 41 |
super().__init__(message) |
| 42 |
self.message = message |
| 43 |
self.status_code = code |
| 44 |
self.http_response = http_response |
| 45 |
self.global_transaction_id = None |
| 46 |
if http_response is not None: |
| 47 |
self.global_transaction_id = http_response.headers.get('X-Global-Transaction-ID') |
| 48 |
self.message = self.message if self.message else self._get_error_message(http_response) |
| 49 |
|
| 50 |
# pylint: disable=fixme |
| 51 |
# TODO: delete this by the end of 2024. |
| 52 |
@property |
| 53 |
def code(self): |
| 54 |
"""The old `code` property with a deprecation warning.""" |
| 55 |
|
| 56 |
warnings.warn( |
| 57 |
'Using the `code` attribute on the `ApiException` is deprecated and ' |
| 58 |
'will be removed in the future. Use `status_code` instead.', |
| 59 |
DeprecationWarning, |
| 60 |
) |
| 61 |
return self.status_code |
| 62 |
|
| 63 |
def __str__(self) -> str: |
| 64 |
msg = 'Error: ' + str(self.message) + ', Status code: ' + str(self.status_code) |
| 65 |
if self.global_transaction_id is not None: |
| 66 |
msg += ' , X-global-transaction-id: ' + str(self.global_transaction_id) |
| 67 |
return msg |
| 68 |
|
| 69 |
@staticmethod |
| 70 |
def _get_error_message(response: Response) -> str: |
| 71 |
error_message = 'Unknown error' |
| 72 |
try: |
| 73 |
error_json = response.json(strict=False) |
| 74 |
if 'errors' in error_json: |
| 75 |
if isinstance(error_json['errors'], list): |
| 76 |
err = error_json['errors'][0] |
| 77 |
error_message = err.get('message') |
| 78 |
elif 'error' in error_json: |
| 79 |
error_message = error_json['error'] |
| 80 |
elif 'message' in error_json: |
| 81 |
error_message = error_json['message'] |
| 82 |
elif 'errorMessage' in error_json: |
| 83 |
error_message = error_json['errorMessage'] |
| 84 |
elif response.status_code == 401: |
| 85 |
error_message = 'Unauthorized: Access is denied due to invalid credentials' |
| 86 |
else: |
| 87 |
error_message = HTTPStatus(response.status_code).phrase |
| 88 |
return error_message |
| 89 |
except: |
| 90 |
return response.text or error_message |