1

I'm writing a fault tolerant HTTP client with the requests library and I want to handle all the exceptions that are defined in requests.exceptions

Here are the exception that are defined within requests.exceptions:

'''
exceptions.BaseHTTPError         exceptions.HTTPError             exceptions.ProxyError            exceptions.TooManyRedirects
exceptions.ChunkedEncodingError  exceptions.InvalidSchema         exceptions.RequestException      exceptions.URLRequired
exceptions.ConnectionError       exceptions.InvalidURL            exceptions.SSLError              
exceptions.ContentDecodingError  exceptions.MissingSchema         exceptions.Timeout  
'''

When I use pylint on my application, I'm getting an error message as described in http://pylint-messages.wikidot.com/messages:e0701 which indicates that the order is not correct. What is the proper order I should be catching the errors in (so as to not mask a more specific error by catching the generic one first), and is there a general purpose way to determine this?

Community
  • 1
  • 1
Ricky Wilson
  • 3,187
  • 4
  • 24
  • 29

2 Answers2

2

Most of the exceptions inherit from RequestException or ConnectionError (which itself inherits from RequestException). Python checks the exceptions in the order you write them in the script. If you want to catch the exceptions individually, put leaf-most exceptions first, followed by ConnectionError and ending with RequestException. Or, just catch RequestException which will catch all of them.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

I wrote a decorator that will handle the requests.exception.RequestException

def handle_reqexcept(func):
    def handle(*args, **kw):
        try:
            return func(*args, **kw)
        except requests.exceptions.RequestException:
            return
    return handle


The actual function i wrote is:

def handle_reqexcept(func):
    '''
    This decorator handles request.excptions
    '''
    @wraps(func)
    def handle(*args, **kw):
        '''
        Handle RequestException
        '''
        try:
            return func(*args, **kw)
        except requests.exceptions.RequestException as error:
            LOGGER.log_error(error)
    return handle
Ricky Wilson
  • 3,187
  • 4
  • 24
  • 29
  • What does this do? If I'm not mistaken, this looks like all it does it catch RequestExceptions (and any exception which inherits it) and silently ignores it by returning None (and thereby loses information on which specific exception occurred), which is not good practice in any language. – Foon Nov 18 '15 at 22:01