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?

2
  • What do you mean "order"? Commented Nov 18, 2015 at 19:57
  • This link should explain Bad Order. Commented Nov 18, 2015 at 20:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.