📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Flask Web Framework Error Handling Flask

Error Handling Flask

5 min read Quiz at the end
Register error handlers for HTTP codes and custom exceptions to return consistent JSON errors.

Error Handling

from flask import jsonify

# Custom error handlers
@app.errorhandler(404)
def not_found(e):
    return jsonify({"error": "Not found"}), 404

@app.errorhandler(500)
def server_error(e):
    return jsonify({"error": "Internal server error"}), 500

@app.errorhandler(ValidationError)
def validation_error(e):
    return jsonify({"error": str(e)}), 422

# HTTP exceptions
from werkzeug.exceptions import abort
abort(404)
abort(403, description="Forbidden")

# Custom exception
class APIError(Exception):
    def __init__(self, message, status_code=400):
        self.message    = message
        self.status_code = status_code

@app.errorhandler(APIError)
def handle_api_error(e):
    return jsonify({"error": e.message}), e.status_code

raise APIError("Email already exists", 409)
Topic Quiz · 2 questions

Test your understanding before moving on

1. What is the purpose of @app.errorhandler(404)?
💡 Error handlers intercept specific HTTP errors and return custom responses.
2. What does abort(404) do?
💡 abort() raises an HTTPException which Flask routes to the error handler.