patternpythonflaskTip
Flask error handling — @app.errorhandler and custom error pages
Viewed 0 times
Flask 2.x+
error handlererrorhandler404500abortcustom errorJSON error
Problem
Default Flask error pages are plain HTML. API endpoints need JSON error responses. Unhandled exceptions show internal stack traces in production.
Solution
Register @app.errorhandler() for HTTP error codes and exception classes. Return JSON for API requests, HTML for browser requests. Use DEBUG=False in production.
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
class APIError(Exception):
def __init__(self, message, status_code=400, code=None):
self.message = message
self.status_code = status_code
self.code = code or 'API_ERROR'
@app.errorhandler(APIError)
def handle_api_error(error):
return jsonify({'error': error.code, 'message': error.message}), error.status_code
@app.errorhandler(404)
def not_found(error):
if request.accept_mimetypes.accept_json:
return jsonify({'error': 'not_found', 'message': 'Resource not found'}), 404
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_error(error):
db.session.rollback() # Rollback any broken transaction
return jsonify({'error': 'internal_error', 'message': 'Something went wrong'}), 500Why
errorhandler() registers a function to call when an HTTP error code is raised (via abort()) or an exception class propagates uncaught. Flask checks Accept headers to determine response format preference.
Gotchas
- Error handlers in blueprints only catch errors from routes within that blueprint (Flask 2.x behavior)
- Registering errorhandler on the app handles errors from all blueprints
- Using abort(404) raises Werkzeug's NotFound exception — handle by registering errorhandler(404)
- PROPAGATE_EXCEPTIONS=True disables error handlers and re-raises for debugger access
Context
Flask apps serving both browser and API clients that need consistent error responses
Revisions (0)
No revisions yet.