Hey I'm wondering how to handle specific error codes. For example, [Errno 111] Connection refused
I want to catch this specific error in the socket module and print something.
If you want to get the error code, this seems to do the trick;
import errno
try:
socket_connection()
except socket.error as error:
if error.errno == errno.ECONNREFUSED:
print(os.strerror(error.errno))
else:
raise
You can look up errno error codes.
ECONNREFUSED appears to be 61 not 111, so hard-coding the value 111 would be a bad idea for portability.else: raise, otherwise all other error codes will be silently ignored!else that pairs with the if. So the else would be at the first indent level, within the except block.os.strerror(error.errno) will convert the error code to a message string. i.e.: os.strerror(104) returns 'Connection reset by peer'On Unix platforms, at least, you can do the following.
import socket, errno
try:
# Do something...
except socket.error as e:
if e.errno == errno.ECONNREFUSED:
# Handle the exception...
else:
raise
Before Python 2.6, use e.args[ 0 ] instead of e.errno.
e.errno instead of e.args[0] is usually preferred (for exceptions that use errnos).socket.error didn't have an errno member. It turns out that before Python 2.6, socket.error wasn't a subclass of IOError and so didn't have an errno member. But of course, before Python 2.6 the except t as e syntax wasn't valid either... I'll update my code.This seems hard to do reliably/portably but perhaps something like:
import socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 4167))
except socket.error, e:
if 'Connection refused' in e:
print '*** Connection refused ***'
which yields:
$ python socketexception.py
*** Connection refused ***
Pretty yucky though.
errno like in the above answers.I'm developing on Windows and found myself in the same predicament. But the error message always contains the error number. Using that information I just convert the exception to a string str(Exception), convert the error code I wanna check for to a string str(socket.errno.ERRORX) and check if the error code is in the exception.
Example for a connection reset exception:
except Exception as errorMessage:
if str(socket.errno.ECONNRESET) in str(errorMessage):
print("Connection reset")
#etc...
This avoids locale specific solutions but is still not platform independent unfortunately.
This is a very good question, but sadly the answer is quite dissapointing to me at least.
There is no pythonic way to do this.
You'll have to lookup for the error code, but you cannot catch ONLY the code you are looking for. Although you can raise if the errno doesn't match, but still, no pythonic way