Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python requests exception handling

People also ask

How does Python handle HTTP exception?

try: # Open a file object for the webpage f = urllib. request. urlopen(imageURL) # Open the local file where you will store the image imageF = open('{0}{1}{2}{3}'.

What is Raise_for_status in Python?

raise_for_status() returns an HTTPError object if an error has occurred during the process. It is used for debugging the requests module and is an integral part of Python requests. Python requests are generally used to fetch the content from a particular resource URI.

What is exception handling in Python with examples?

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.


Assuming you did import requests, you want requests.ConnectionError. ConnectionError is an exception defined by requests. See the API documentation here.

Thus the code should be :

try:
   requests.get('http://www.google.com')
except requests.ConnectionError:
   # handle the exception

As per the documentation, I have added the below points:-

  1. In the event of a network problem (refused connection e.g internet issue), Requests will raise a ConnectionError exception.

    try:
       requests.get('http://www.google.com')
    except requests.ConnectionError:
       # handle ConnectionError the exception
    
  2. In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception. Response.raise_for_status() will raise an HTTPError if the HTTP request returned an unsuccessful status code.

    try:
       r = requests.get('http://www.google.com/nowhere')
       r.raise_for_status()
    except requests.exceptions.HTTPError as err:
       #handle the HTTPError request here
    
  3. In the event of times out of request, a Timeout exception is raised.

    You can tell Requests to stop waiting for a response after a given number of seconds, with a timeout arg.

    requests.get('https://github.com/', timeout=0.001)
    # timeout is not a time limit on the entire response download; rather, 
    # an exception is raised if the server has not issued a response for
    # timeout seconds
    
  4. All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException. So a base handler can look like,

    try:
       r = requests.get(url)
    except requests.exceptions.RequestException as e:
       # handle all the errors here
    

Actually, there are much more exceptions that requests.get() can generate than just ConnectionError. Here are some I've seen in production:

from requests import ReadTimeout, ConnectTimeout, HTTPError, Timeout, ConnectionError

try:
    r = requests.get(url, timeout=6.0)
except (ConnectTimeout, HTTPError, ReadTimeout, Timeout, ConnectionError):
    continue

for clarity, that is

except requests.ConnectionError:

NOT

import requests.ConnectionError

 

You can also catch a general exception (although this isn't recommended) with

except Exception: