How can I implement a custom error handler in Flask?


Did you know?

You can register exception handlers to a Flask app based on an exception class or response status code.

An example👇

from flask import Flask, jsonify, abort

app = Flask(__name__)


class ValidationException(Exception):
    code = 500
    message = "Unknown error"


@app.errorhandler(ValidationException)
def handle_validation_exception(exc):
    return (
        jsonify({"msssage": exc.message, "exception": exc.__class__.__name__}),
        exc.code,
    )


@app.errorhandler(500)
def handle_internal_server_error(exc):
    return jsonify({"msssage": "Oops!", "exception": "Internal server error"}), 500


@app.route("/")
def hello():
    raise ValidationException()