Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Error Codes in Python and Using Meanful Error Names

I understand the basic try: except: finally: syntax for pythons error handling. What I don't understand is how to find the proper error names to make readable code.

For example:

try:
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     s.connect((HOST, PORT))
     s.settimeout(60)               
     char = s.recv(1)

except socket.timeout:
    pass

so if socket raises a timeout, the error is caught. How about if I am looking for a connection refused. I know the error number is 10061. Where in the documentation do I look to find a meaning full name such as timeout. Would there be a similar place to look for other python modules? I know this is a newbie question but I have been putting in error handling my my code for some time now, without actually knowing where to look for error descriptions and names.

EDIT:

Thanks for all your responses.

would

except socket.error, exception:
    if exception.errno == ETIMEDOUT:
         pass

achieve the same result as

except socket.timeout:
    pass
like image 684
Richard Avatar asked Nov 25 '11 14:11

Richard


2 Answers

To achieve what you want, you'll have to grab the raised exception, extract the error code stored into, and make some if comparisons against errno codes:

try:
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     s.connect((HOST, PORT))
     s.settimeout(60)               
     char = s.recv(1)
except socket.error, exception:
    if exception.errno == errno.ECONNREFUSED:
        # this is a connection refused
    # or in a more pythonic way to handle many errors:
    {
       errno.ECONNREFUSED : manage_connection_refused,
       errno.EHOSTDOWN : manage_host_down,
       #all the errors you want to catch
    }.get(exception.errno, default_behaviour)()
except socket.timeout:
    pass

with :

def manage_connection_refused():
   print "Connection refused"

def manage_host_down():
   print "Host down"

def default_behaviour():
   print "error"
like image 79
Cédric Julien Avatar answered Oct 10 '22 18:10

Cédric Julien


You will get an error with an errno, which is described in the errno documentation. 10061 is only valid for WinSock.

like image 25
unbeli Avatar answered Oct 10 '22 17:10

unbeli