Error Handling (Flask)
Error handling in Flask lets you customize what happens when something goes wrong, replacing the default error pages with your own. You register handlers with @app.errorhandler(code) and raise HTTP errors with abort().
Flask
By default Flask shows a plain 404 or 500 page. With @app.errorhandler(404) you register a function that returns your own template and status code for that error, giving users a branded, helpful page instead.
abort(404) (from flask) immediately stops the view and triggers the matching error handler — handy for 'not found' or 'forbidden' cases. You can register handlers for HTTP codes (404, 403, 500) and even for specific exception classes to catch your own errors.
For APIs, error handlers commonly return jsonify({'error': ...}) with the right status code so clients get structured error responses. Note that in debug mode the interactive debugger replaces your 500 handler, so test error pages with debug off.
Syntax
@app.errorhandler(404)
def not_found(e): ...Examples
Python
from flask import abort, jsonify
@app.errorhandler(404)
def not_found(e):
return jsonify(error="Not found"), 404
@app.route("/item/<int:i>")
def item(i):
if i > 100:
abort(404)
return f"Item {i}"