I have a question about flask error handler. When I want to handle 404 error I use this code:
@app.errorhandler(404)
def page_not_found(e):
return render_template("404.html")
Why I should pass the (e) to the function? Thanks! :)
e
is the exception raised, triggering the handler to be called.
You can register the same error handling function for multiple error codes, and you can use that argument passed in to determine exactly for what error it was called or use that code in a generic template:
@application.errorhandler(404)
@application.errorhandler(401)
@application.errorhandler(500)
def http_error_handler(error):
return render_template("error.html", error=error)
From the Error Handlers documentation:
An error handler is a function, just like a view function, but it is called when an error happens and is passed that error.
Bold emphasis mine.
Note that it is an exception instance; for HTTP error codes, that'll be an instance of a subclass of the HTTPException
class (Werkzeug defines several such subclasses). Such instances have a .code
attribute if you really want to match against the HTTP code:
if error.code == 404:
# not found error