Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get HTTP Error code from requests.exceptions.HTTPError

I am catching exceptions like this,

def get_url_fp(image_url, request_kwargs=None):
    response = requests.get(some_url, **request_kwargs)
    response.raise_for_status()
    return response.raw


try:
   a = "http://example.com"
   fp = get_url_fp(a)

except HTTPError as e:
    # Need to check its an 404, 503, 500, 403 etc.
like image 752
Shiplu Mokaddim Avatar asked Oct 13 '13 05:10

Shiplu Mokaddim


People also ask

How do I get exception status code in Python?

Python exceptions do not have "codes". You can create a custom exception that does have a property called code and then you can access it and print it as desired. This answer has an example of adding a code property to a custom exception.

How do you raise the HTTP exception in Python?

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.

What is HTTPError?

February 21, 2019. Sometimes when you try to visit a web page, you're met with an HTTP error message. It's a message from the web server that something went wrong. In some cases it could be a mistake you made, but often, it's the site's fault. Each type of error has an HTTP error code dedicated to it.


2 Answers

The HTTPError carries the Response object with it:

def get_url_fp(image_url, request_kwargs=None):
    response = requests.get(some_url, **request_kwargs)
    response.raise_for_status()
    return response.raw


try:
    a = "http://example.com"
    fp = get_url_fp(a)

except HTTPError as e:
    # Need to check its an 404, 503, 500, 403 etc.
    status_code = e.response.status_code
like image 103
Lukasa Avatar answered Oct 07 '22 13:10

Lukasa


If you need only status_code or message error. You can use this code:

try:
  [YOUR CODE]
except requests.exceptions.HTTPError as err:
  print(err.response.status_code)
  print(err.response.text)

Reference: Source code for requests.exceptions

like image 2
calraiden Avatar answered Oct 07 '22 14:10

calraiden