Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 386
Aashish P Avatar asked Mar 22 '23 10:03

Aashish P


1 Answers

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.

like image 172
mata Avatar answered Apr 24 '23 23:04

mata