I'm implementing an asyncore-based IRC bot in python and am having trouble catching exceptions that occurr within the methods of asyncore-dispatched classes. Here is my minimal example:
#!/usr/bin/env python
import asyncore
import socket
import sys
class foo (asyncore.dispatcher):
def __init__ (self, host, port):
asyncore.dispatcher.__init__ (self)
self.create_socket (socket.AF_INET, socket.SOCK_STREAM)
self.connect ((host, port))
def handle_exception(excType, excValue, trace):
print "Blah! Exception!"
quit()
sys.excepthook = handle_exception
foo ("127.0.0.1", 19991)
asyncore.loop()
It attempts to make a connection to 127.0.0.1:19991 which doesn't have anything, so it results in a connection refused error and throws an exception. The problem here is that sys.excepthook, which is the handle_exception function, does not appear to catch it:
error: uncaptured python exception, closing channel <__main__.foo 127.0.0.1:19991 at
0x7fad23eaeab8> (<class 'socket.error'>:[Errno 111] Connection refused [/usr/lib/python2.7
/asyncore.py|read|83] [/usr/lib/python2.7/asyncore.py|handle_read_event|446] [/usr/lib/python2.7
/asyncore.py|handle_connect_event|454])
If I put something like 1/0 before the foo ("127.0.0.1", 19991) call, the exception handler works as expected. Is it possible to make the exception handler function catch exceptions that happen inside asyncore classes? If so, how? This is with Python v2.7.6.
Override the handle_error
method of dispatcher
.