Spade
Spade

Reputation: 2280

Appropriate Exception to raise during API access failure

When coding a class that provides abstraction over one or more HTTP APIs that it transparently consumes, what is the appropriate Exception to raise when the service request ends up in a HTTP 404 or similar?

The class is intended as a composite object for consumers who have a high-level overview of what services are being consumed but would appreciate a specific exception for failures at the API access level. Of course, one could always write and raise a Custom Exception Object:

class WebServiceUnresponsive(Exception):
    pass

But going through, Standard Python Exceptions, I am not sure if I am overlooking a suitable candidate. What is the best practice if not this?

Upvotes: 2

Views: 1379

Answers (1)

TemporalWolf
TemporalWolf

Reputation: 7952

Use requests:

requests.exceptions contains a multitude of built-in HTTP exceptions, and includes a specific response.raise_for_status(), which does all the heavy lifting for you (example from the link):

>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404

>>> bad_r.raise_for_status()
Traceback (most recent call last):
  File "requests/models.py", line 832, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error

If you aren't using requests directly, you can from requests import exceptions and then throw your own.

if exception_encountered(req):
    raise exceptions.HTTPError("Got a 404 yo... server says there's nothing there :(")

Upvotes: 3

Related Questions