How to catch all exceptions in a flask?

Perhaps I don't see something in the documentation .

I would like to not just handle some HTTP errors, but all exceptions. The reason is I would like to register them using my own logic (sounds like reinventing the wheel, but I need full control over the logging). I would not want the server to be on its knees for an exception, but the bomb is only for this particular request.

This is how I run Flask now. This is where app.run starts the server. How can I teach him to call an exception handler method whenever an exception occurs?

 def main(): args = parse_args() app.config['PROPAGATE_EXCEPTIONS'] = True flask_options = {'port' : args.port} if args.host == 'public': flask_options['host'] = '0.0.0.0' app.run(**flask_options) if __name__ == '__main__': _sys.exit(main()) 
+8
flask exception-handling configuration
source share
1 answer

You should use errorhandler , see the documentation http://flask.pocoo.org/docs/patterns/errorpages/#error-handlers and http://flask.pocoo.org/docs/api/#flask.Flask.errorhandler . This allows you to receive all exceptions that occur in dispatchers, but not to handle exceptions in error handlers. For example, to handle all exceptions:

 @app.errorhandler(Exception) def all_exception_handler(error): return 'Error', 500 

Be that as it may, I prefer explicit exception handlers or use decorators (class-based views) for these cases.

+14
source share

All Articles