23

I'd like to raise a Python-standard exception when an HTTP response code from querying an API is not 200, but what specific exception should I use? For now I raise an OSError:

if response.status_code != 200:
  raise OSError("Response " + str(response.status_code)
                  + ": " + response.content)

I'm aware of the documentation for built-in exceptions.

1
  • Really depends on what the error is. If it's caused by bad input (like an unauthorized API key) then ValueError would be appropriate. I can't think off the top of another built-in exception that would apply (aside form Exception :p) so you'd probably want to craft your own exceptions in that case as the accepted answer suggests. Commented Jan 12, 2021 at 19:33

2 Answers 2

37

You can simply call Response.raise_for_status() on your response:

>>> import requests
>>> url = 'http://stackoverflow.com/doesnt-exist'
>>> r = requests.get(url)
>>>
>>> print r.status_code
404
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 831, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found

This will raise a requests.HTTPError for any 4xx or 5xx response.

See the docs on Response Status Code for a more complete example.


Note that this does not exactly do what you asked (status != 200): It will not raise an exception for 201 Created or 204 No Content, or any of the 3xx redirects - but this is most likely the behavior you want: requests will just follow the redirects, and the other 2xx are usually just fine if you're dealing with an API.

Sign up to request clarification or add additional context in comments.

Comments

8

The built-in Python exceptions are probably not a good fit for what you are doing. You will want to subclass the base class Exception, and throw your own custom exceptions based on each scenario you want to communicate.

A good example is how the Python Requests HTTP library defines its own exceptions:

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.

In the rare event of an invalid HTTP response, Requests will raise an HTTPError exception.

If a request times out, a Timeout exception is raised.

If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.

All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.

3 Comments

If you are in fact using the Requests library, this is probably what you want: docs.python-requests.org/en/latest/api/…
Those links throw 404s..... :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.