how to handle "getaddrinfo failed"?

RogerZ picture RogerZ · Jan 30, 2011 · Viewed 15.2k times · Source

Hallo, i have problem. i use mechanize, python 2.7 to connect some sites (the code is not important right now) i have list of sites and i connect to them one by now. When it happens the site from my list doesn't exist i get error:

urllib2.URLError: [Errno 11004] getaddrinfo failed

I tried to handle it by doing this:

             except mechanize.URLError, e:
                    result = str(e.reason)

or

             except urllib2.URLError, e:
                    result = str(e.reason)

or even

             except Exception, e:
                    result = str(e)

But it just don't want to work.

How to solve this? When this error happens i just want to print something like "connection failed" and move to the next address on the list. How to catch this error by except?

Answer

Jochen Ritzel picture Jochen Ritzel · Jan 30, 2011

Random guess but try:

import socket

try:
   ...
except socket.gaierror:
   pass

socket.gaierror is the "[Errno 11004] getaddrinfo failed" error.

You can easily figure out the exception if you do

try:
    ...
except:
    import sys
    # prints `type(e), e` where `e` is the last exception
    print sys.exc_info()[:2]