Exception Handling in TCPServer (was; Problem exiting application in Windows Console.)

Steve Holden steve at holdenweb.com
Wed Nov 8 20:02:16 CET 2006

Ant wrote:
> Ant wrote:
> ....
>> OK, I've narrowed the problem back to the way HTTPServer (actually its
>> TCPServer parent) handles exceptions thrown by the process_request
>> method by catching them all, and then calling a handle_error method.
>> There doesn't seem to be a way of getting at the exception thrown
>> however - does anyone know how I can get this information?
> Hmm. Lonely topic ;-)
> I've found a way to solve the problem, by creating a subclass of
> HTTPServer which overrides the handle_error method:
> class HelpServer(HTTPServer):
>     def handle_error(self, request, client_address):
>         exception_line = inspect.trace()[-1][-2][0]
>         if "sys.exit" in exception_line:
>             print "Trying to exit again!"
>             sys.exit(0)
>         else:
>             HTTPServer.handle_error(self, request, client_address)
> This seems a really nasty hack though - any ideas for a cleaner way to
> do it?
First of all, five hour response time is a high expectation, you must be 
a Platinum customer :-)

Secondly, while a try/except catching all exceptions *is* unusual it's 
justifiable in a server context (though some logging and/or analysis 
certainly wouldn't go amiss).

Thirdly your "ugly hack" *could* be replaced by something cleaner with 
more analysis of the trace structure, but given how infrequently this 
code is going to run and the low probability that anything else will 
trigger the hook I'd be happy with it as it is. But that's just me ...

Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden

More information about the Python-list mailing list