How to differentiate timeout error and other `URLError`s in Python?
Question: How to differentiate timeout error and other `URLError`s in Python?

**EDIT**

When I catch a `URLError`, it can be `Temporary failure in name resolution` or
`timeout`, or some other error? How can I tell one from another?


Answer: I use code like Option 2, below... but for a comprehensive answer, look at
[Michael Foord's urllib2
page](http://www.voidspace.org.uk/python/articles/urllib2.shtml)

If you use either option 1 or option 2 below, you can add as much intelligence
and branching as you like in the except clauses by looking at `e.code` or
`e.reason`

Option 1:

    
    
    from urllib2 import Request, urlopen, URLError, HTTPError
    req = Request(someurl)
    try:
        response = urlopen(req)
    except HTTPError, e:
        print 'The server couldn\'t fulfill the request.'
        print 'Error code: ', e.code
    except URLError, e:
        print 'We failed to reach a server.'
        print 'Reason: ', e.reason
    else:
        # everything is fine
    

Option 2:

    
    
    from urllib import urlencode
    from urllib2 import Request
    # insert other code here...
        error = False
        error_code = ""
        try:
            if method.upper()=="GET":
                response = urlopen(req)
            elif method.upper()=="POST":
                response = urlopen(req,data)
        except IOError, e:
            if hasattr(e, 'reason'):
                #print 'We failed to reach a server.'
                #print 'Reason: ', e.reason
                error = True
                error_code = e.reason
            elif hasattr(e, 'code'):
                #print 'The server couldn\'t fulfill the request.'
                #print 'Error code: ', e.code
                error = True
                error_code = e.code
        else:
            # info is dictionary of server parameters, such as 'content-type', etc...
            info = response.info().dict
            page = response.read()
    

