0

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! :)

Dok
  • 71
  • 8
  • `e` is for your error traceback. And also https://stackoverflow.com/questions/27760113/how-can-i-implement-a-custom-error-handler-for-all-http-errors-in-flask – Arpit Solanki Jun 12 '17 at 19:10
  • The `e` will hold the object of the exception that was raised so you can use it for contextual information to provide the *why* it failed in your return, or to handle it in your own logic on what you want to do on certain failures. This is explained in the [documentation](http://flask.pocoo.org/docs/0.12/patterns/errorpages/#error-handlers) – idjaw Jun 12 '17 at 19:11

2 Answers2

3

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

I'm guessing it is holding the exception so if you want to return it to know what went wrong. Though I am not familiar with this, or it if it is a parent it may need an argument supplied to it to check the error and handle it properly.

Cai Martin
  • 17
  • 5