Flask comes with a handy abort() function that aborts a request with an HTTP error code early. It will also provide a plain black and white error page for you with a basic description, but nothing fancy.
Depending on the error code it is less or more likely for the user to actually see such an error.
The following error codes are some that are often displayed to the user, even if the application behaves correctly:
An error handler is a function, just like a view function, but it is called when an error happens and is passed that error. The error is most likely a HTTPException, but in one case it can be a different error: a handler for internal server errors will be passed other exception instances as well if they are uncaught.
An error handler is registered with the errorhandler() decorator and the error code of the exception. Keep in mind that Flask will not set the error code for you, so make sure to also provide the HTTP status code when returning a response.
Here an example implementation for a “404 Page Not Found” exception:
from flask import render_template
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
An example template might be this:
{% extends "layout.html" %}
{% block title %}Page Not Found{% endblock %}
{% block body %}
<h1>Page Not Found</h1>
<p>What you were looking for is just not there.
<p><a href="{{ url_for('index') }}">go somewhere nice</a>
{% endblock %}