87

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.
Leon Young
  • 585
  • 2
  • 6
  • 14
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187

3 Answers3

165

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
Lukasa
  • 14,599
  • 4
  • 32
  • 34
  • 6
    one of the keys here is you also need to call response.raise_for_status(). reference here: http://docs.python-requests.org/en/latest/user/quickstart/#response-status-codes – nommer Apr 14 '16 at 21:40
  • Thanks a ton. Seems like this is the only way to handle errors in any HTTP methods using python `requests`. – Gokul Aug 02 '18 at 09:33
  • Curious. I'm seeing e.response as an object of type urllib3.response.HTTPResponse. – Edward Falk Dec 27 '19 at 19:36
7

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

calraiden
  • 1,686
  • 1
  • 27
  • 37
-10

This is my code to get errors codes in HTTP

def tomcat_status(ip,port,url):
    try:
    # you can give your own url is
       r = urllib2.urlopen('http://'+ip+':'+port+'/'+url)
       return r.getcode()
     except urllib2.HTTPError as e:
       return e.code
    except urllib2.URLError as f:
       return 1
print tomcat_status(ip,tomcat_port,ping_url)
Raj
  • 8
  • 4
  • 7
    The OP was specific about using the Requests package. Your answer is using urllib2. While it may be technically accurate and represent an alternative way to do a thing it is not helpful in this context. It also appears to be poorly formatted. – e.thompsy Aug 24 '17 at 17:41
  • This is just another alternative to get the Status code, as both request and urllib are default in python , we can use either of them. – Raj Sep 13 '17 at 03:21