Python Forum
sys.excepthook = handle_exception not invoket or trigeret
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sys.excepthook = handle_exception not invoket or trigeret
#1
i have this simple flask app :

    def handle_exception(exc_type, exc_value, exc_traceback):
        print("Hello")
    
    dd = "test"
    sys.excepthook = handle_exception
    logger.info("a %s- b: %s" % dd)
    # the logger above will raise exception 
    
    
    if __name__ == '__main__':
        # Start the app
        app.run(host='0.0.0.0', threaded=True)
the handle_exception never called
but in the stdout/err Im getting :

   Traceback (most recent call last):
      File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1434, in _exec
        pydev_imports.execfile(file, globals, locals)  # execute the script
      File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
        exec(compile(contents+"\n", file, 'exec'), glob, loc)
      File "C:/git/app/app.py", line 132, in <module>
        logger.info("a %s- b: %s" % dd)
    TypeError: not enough arguments for format string
how to make it call the handle_exception? there i like to handle all exception that are not Were caughtאם
Reply
#2
In the example you specified, the handle_exception will be called(even tested it). It won't be called inside your view functions like :
def handle_exception(exc_type, exc_value, exc_traceback):
    print("Hello")
     
dd = "test"
sys.excepthook = handle_exception

@app.route('/')
def hello_world():
    logger.info("a %s- b: %s" % dd) # this will raise exception but won't call handle_exception
    return 'Hello, World!'
     
if __name__ == '__main__':
    # Start the app
    app.run(host='0.0.0.0', threaded=True)
handle_exception won't be called because flask is handling errors in views for you. You can specify you own error handler:
@app.errorhandler(Exception)
def unhandled(error):
    return 'some error message'

@app.route('/')
def hello_world():
    logger.info("a %s- b: %s" % dd) # this will raise exception and call unhandled
    return 'Hello, World!'
     
if __name__ == '__main__':
    # Start the app
    app.run(host='0.0.0.0', threaded=True)
docs: https://flask.palletsprojects.com/en/1.1...rhandling/
Reply
#3
Thansk for the quick response the problem with the solution you gave me is that the unhandled(error) function do invoke
but it do not contain the detailed exception Traceback i showed above:

result = {TypeError} not enough arguments for format string
 args = {tuple: 1} not enough arguments for format string
  0 = {str} 'not enough arguments for format string'
  __len__ = {int} 1
but when i look at the Exception in
@app.errorhandler(Exception)
i do see all the info from Traceback , how do I pass this info to the unhandled(error) function ?
Reply
#4
you can access that from sys.exc_info:
import traceback
import sys

@app.errorhandler(Exception)
def unhandled():
    # get individual values
    exc_type, exc_value, exc_traceback = sys.exc_info() 
    # or build traceback
    tb = traceback.format_exception(*sys.exc_info())
    # or print it right away
    traceback.print_exception(*sys.exc_info())
    # you can specify where to print as well with 'file'
    traceback.print_exception(*sys.exc_info(), file='your_file.log')
    return 'some error message'

Btw if you want this just because you want to log unhandled exceptions to a file then you need to configure logging as it is mentioned in other thread:
from logging import dictConfig

dictConfig({
    'version': 1,
    'formatters': {'default': {
        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
    }},
    'handlers': {'wsgi': {
        'class': 'logging.handlers.RotatingFileHandler',
        'formatter': 'default',
        'filename': 'hello.log'
    }},
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi']
    }
})
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020