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 .
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.
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 (eg 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.