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?
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?
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)
socket.timeout
–
Tomasine hasattr(e,'reason') and isinstance(e.reason, socket.timeout)
as HttpError
at least doesn't have a reason
attribute in Python 2.6. –
Saucy socket.timeout
works for me with Python 2.7.6. –
Chloro 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 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)
© 2022 - 2024 — McMap. All rights reserved.
timeout
parameter doesn't limit neither the total connection time nor total read (response) time. – Okra