Flask default error handler not being called

11,738

Solution 1

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).

Solution 2

You can do this like this:

app.config['TRAP_HTTP_EXCEPTIONS']=True
app.register_error_handler(Exception, defaultHandler)

Solution 3

Check that render_template('defaultError.html') and e.code do not raise any exception. For example I'm not sure that any your exceptions can have code attribute, try very simple example:

@err.app_errorhandler(Exception)
def defaultHandler(e):
   return 'error handler there', 500
Share:
11,738

Related videos on Youtube

bqui56
Author by

bqui56

Updated on September 14, 2022

Comments

  • bqui56
    bqui56 over 1 year

    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.

  • bqui56
    bqui56 over 10 years
    No exceptions are being raised that I can identify (running using the flask in-built server). I would have thought my 500 mapping would have been hit if it were anyway.
  • tbicr
    tbicr over 10 years
    For me it work fine, flask==0.10.1 and wergzeug=0.9.4. About user exceptions look why your code do not handled there github.com/mitsuhiko/flask/blob/master/flask/app.py#L1475.