Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask default error handler not being called

I have an errors.py module to map errors to templates. I was wanting to add a default error handler and came across: http://flask.pocoo.org/mailinglist/archive/2012/7/12/default-error-handler/#cbeb8809dc0da7133f14b99e16f31d6b

I'm using Blueprint to modularize things and the errors module has the following mappings:

@err.app_errorhandler(403)
def forbidden(e):
   return render_template('403.html'), 403

@err.app_errorhandler(500)
def serverError(e):
   return render_template('500.html'), 500

@err.app_errorhandler(Exception)
def defaultHandler(e):
   return render_template('defaultError.html'), e.code

The specific mappings (403, 500) work fine if I abort to them (or induce them naturally), but if I abort to anything else (404 etc.) the defaulHandler() is not invoked.

like image 399
bqui56 Avatar asked Dec 16 '13 05:12

bqui56


People also ask

How do you send an error response in Flask?

Flask gives you the ability to raise any HTTP exception registered by Werkzeug. However, the default HTTP exceptions return simple exception pages. You might want to show custom error pages to the user when an error occurs. This can be done by registering error handlers.

How does a Flask handle 404?

To handle 404 Error or invalid route error in Flask is to define a error handler for handling the 404 error. @app. errorhandler(404) def invalid_route(e): return "Invalid route." Now if you save the changes and try to access a non existing route, it will return “Invalid route” message.

How does Python handle 500 internal server error?

Make sure debug mode is off, then try again. Here is a comment directly from the code itself: Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used.


2 Answers

You can do this like this:

app.config['TRAP_HTTP_EXCEPTIONS']=True
app.register_error_handler(Exception, defaultHandler)
like image 165
ther Avatar answered Oct 20 '22 15:10

ther


It appears that a 404 doesn't actually raise an exception in the flask code so the default handler doesn't have any reason to be hit. I can make it hit if I add raise Exception to one of my url mappings and navigate to it.

Of course, if you have a 500 error mapping, the exception would turn into a server side error and therefore it would fall into that catchment, so I am failing to see the use of the Exception catching at this point (I can't think of any cases where it would catch something that a 500 errorhandler would not).

like image 26
bqui56 Avatar answered Oct 20 '22 17:10

bqui56