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?