Handling urllib2's timeout? - Python
Asked Answered
A

2

68

I'm using the timeout parameter within the urllib2's urlopen.

urllib2.urlopen('http://www.example.org', timeout=1)

How do I tell Python that if the timeout expires a custom error should be raised?


Any ideas?

Altdorf answered 26/4, 2010 at 10:3 Comment(1)
T
105

There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

At the very simplest, you would catch urllib2.URLError:

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

The following should capture the specific error raised when the connection times out:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)
Tomasine answered 26/4, 2010 at 10:30 Comment(7)
This will not work in Python 2.7, as URLError does not catch socket.timeout anymoreFrisian
@TalWeiss thanks, added an additional catch for socket.timeoutTomasine
As for Python 2.7.5 timeouts are caught by urllib2.URLError.Lamb
@Tomasine Thanks, moreover it should be hasattr(e,'reason') and isinstance(e.reason, socket.timeout) as HttpError at least doesn't have a reason attribute in Python 2.6.Saucy
I don't understand Tal and Nicolas's comments, but socket.timeout works for me with Python 2.7.6.Chloro
For what it's worth, with python 2.6.6 a timeout trying to connect seems to result in the urllib2.URLError. A timeout while reading the response from a slow server seems to result in socket.timeout. So overall, catching both allows you to distinguish these cases.Monied
I am using python 2.7 and I just could handle TimeoutException with 'urllib2.URLError' instead of 'socket.timeout'Krenn
U
20

In Python 2.7.3:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
    print type(e)    #not catch
except socket.timeout as e:
    print type(e)    #catched
    raise MyException("There was an error: %r" % e)
Uzia answered 31/1, 2013 at 18:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.