Changing default behavior of handling unspoken exceptions in python

I went through registering uncaught exceptions in Python . "And I tried this:

import web import sys app = web.application(( '/test', 'test'), globals()) def test_func(e_type, value, traceback): print "Handled exception here.." class test: def GET(self): a = 1/0 if __name__ == "__main__": sys.excepthook = test_func app.run() 

Here you can easily see if a GET /test request comes in, I intentionally raise a ZerDivisionError . Since I exceeded sys.excepthook , I expect the test_func method to execute on a ZeroDivisionError .

While this piece of code does not work as expected. I noticed that when I try to override excepthook in standalone code (not in a web application), it works fine. The new method (overriden) is called correctly.

Any idea why this is a different behavior?

+4
source share
2 answers

Using web.py, one way to throw exceptions is to add a custom processor :

 ... def error_processor(handler): try: handler() except: # do something reasonable to handle the exception return 'something happened...' app.add_processor(error_processor) app.run() ... 

Otherwise, web.py will catch an exception and display a default error message.

+5
source

Python doc says

sys.excepthook (type, value, trace)

This function displays the specified trace and exception in sys.stderr.

Thus, this sys.excepthook is called when an exception is to be printed on the terminal. Now you see that web.py itself handles exceptions. If you do not assign sys.excepthook, the webpage catches the exception and displays the exception in the browser. And since web.py itself handles exceptions, setting sys.excepthook does not change. If web.py did not handle this exception itself, it would not be sys.excepthook and sys.excepthook would be called.

If you really want to handle the exception yourself in this code, try finding the web.py document and source code to find out how web.py handles the exceptions and customizes them.

python doc also says

sys.__excepthook__

These objects contain the initial displayhook and excepthook values ​​at the beginning of the program. They are saved so that displayhook and excepthook can be restored if they are replaced by broken objects.

So my guess is web.py, so your custom handler is not called.

+2
source

Source: https://habr.com/ru/post/1502249/


All Articles