简体   繁体   中英

Change default behavior of uncaught exception handling in python

I went through " Logging uncaught exceptions in Python ". And, I have 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 GET /test request comes in, I am deliberately raising ZerDivisionError . As i have overriden sys.excepthook , I expect method test_func to execute on ZeroDivisionError .

Whereas, this piece of code is not working as per expectation. I have observed that when i try to override excepthook in standalone code (not in web-app), it works fine. New method(overriden) is called properly.

Any idea why is this different behavior ?

Using web.py, one way of catching exceptions yourself would be 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 the exception and show a default error message instead.

Python doc says

sys.excepthook(type, value, traceback)

This function prints out a given traceback and exception to sys.stderr.

So this sys.excepthook is called when a exception needs to printed to terminal. Now you see, web.py itself handles the exceptions. If you dont assign the sys.excepthook, webpy captures the exception and shows the exception in browser. And as web.py is itself handling the exceptions, setting sys.excepthook makes no change. If web.py didn't handle the exception itself, then it would be uncaught and sys.excepthook would be called.

If you really want to handle exception yourself in this code, try searching web.py doc and source code to figure out how web.py handles exceptions and customize that.

python doc also says

sys.__excepthook__

These objects contain the original values of displayhook and excepthook at the start of the program. They are saved so that displayhook and excepthook can be restored in case they happen to get replaced with broken objects.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM