Error pages

Displaying a browser's default error pages to the end user is jarring as the user loses all context of your app, and they must hit the back button to return to your site. To display your own templates when an error is returned with the Flask abort() function, use the errorhandler decorator function:

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

The errorhandler is also useful to translate internal server errors and HTTP 500 code into user-friendly error pages. The app.errorhandler() function may take either one or many HTTP status codes to define which code it will act on. The returning of a tuple instead of just an HTML string allows you to define the HTTP status code of the Response ...

Get Mastering Flask now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.