4

I'm using the Python Requests library to call an API that may return custom error messages in it's JSON response, i.e. something like this:

{
    "error": "TOKEN INVALID"
}

I would like to have a custom exception class with this error message as the message, but otherwise use Requests error handling as much as possible. From other questions it appears that the correct way to do this would be something like this:

class MyCustomAPIError(requests.exceptions.HTTPError):
    pass

response = requests.request('GET', url)
try:
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    msg = e.response.json().get('error')
    raise MyCustomAPIError(msg)

This however raises two exceptions, the original HTTPError first and then

During handling of the above exception, another exception occurred:

... my custom error

which doesn't seem very elegant. I could suppress the first exception by using

raise MyCustomAPIError(msg) from None

but that seems rather hacky. Is this the intended way to do this or am I missing a simpler solution?

gmolau
  • 2,815
  • 1
  • 22
  • 45
  • Looking at https://www.python.org/dev/peps/pep-0409/ I think maybe it's the intended way, although I too would love for someone to expand on the correct way to do this. – t-bone Sep 22 '20 at 10:23

0 Answers0