File: api_exception.py

package info (click to toggle)
python-ibm-cloud-sdk-core 3.19.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 672 kB
  • sloc: python: 4,428; makefile: 26; sh: 25
file content (90 lines) | stat: -rw-r--r-- 3,653 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# coding: utf-8

# Copyright 2019 IBM All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import warnings
from http import HTTPStatus
from typing import Optional

from requests import Response


class ApiException(Exception):
    """Custom exception class for errors returned from operations.

    Args:
        code: HTTP status code of the error response.
        message: The error response body. Defaults to None.
        http_response: The HTTP response of the failed request. Defaults to None.

    Attributes:
        code (int): HTTP status code of the error response.
        message (str): The error response body.
        http_response (requests.Response): The HTTP response of the failed request.
        global_transaction_id (str, optional): Globally unique id the service endpoint has given a transaction.
    """

    def __init__(self, code: int, *, message: Optional[str] = None, http_response: Optional[Response] = None) -> None:
        # Call the base class constructor with the parameters it needs
        super().__init__(message)
        self.message = message
        self.status_code = code
        self.http_response = http_response
        self.global_transaction_id = None
        if http_response is not None:
            self.global_transaction_id = http_response.headers.get('X-Global-Transaction-ID')
            self.message = self.message if self.message else self._get_error_message(http_response)

    # pylint: disable=fixme
    # TODO: delete this by the end of 2024.
    @property
    def code(self):
        """The old `code` property with a deprecation warning."""

        warnings.warn(
            'Using the `code` attribute on the `ApiException` is deprecated and'
            'will be removed in the future. Use `status_code` instead.',
            DeprecationWarning,
        )
        return self.status_code

    def __str__(self) -> str:
        msg = 'Error: ' + str(self.message) + ', Status code: ' + str(self.status_code)
        if self.global_transaction_id is not None:
            msg += ' , X-global-transaction-id: ' + str(self.global_transaction_id)
        return msg

    @staticmethod
    def _get_error_message(response: Response) -> str:
        error_message = 'Unknown error'
        try:
            error_json = response.json(strict=False)
            if 'errors' in error_json:
                if isinstance(error_json['errors'], list):
                    err = error_json['errors'][0]
                    error_message = err.get('message')
            elif 'error' in error_json:
                error_message = error_json['error']
            elif 'message' in error_json:
                error_message = error_json['message']
            elif 'errorMessage' in error_json:
                error_message = error_json['errorMessage']
            elif response.status_code == 401:
                error_message = 'Unauthorized: Access is denied due to invalid credentials'
            else:
                error_message = HTTPStatus(response.status_code).phrase
            return error_message
        except:
            return response.text or error_message