Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

errorhandler in separate blueprint is not working

I am currently working on an app using flask. Whenever I am encountering an error, I am raising it using abort, for example abort(404).

I created a new blueprint for error handling, and included the following files in the errors blueprint:

app/errors/__init__.py

from flask import Blueprint

bp = Blueprint('errors', __name__)

from app.errors import handlers

app/errors/handlers.py

from app.errors import bp
from flask import jsonify, make_response


@bp.errorhandler(404)
def not_found_error():
    return make_response(jsonify({"error: ", "Not found"}), 404)

I also registered the blueprint as follows:

app/__init__.py

from app.errors import bp as errors_bp
app.register_blueprint(errors_bp)

However, when I am encountering the error, I get an HTML response back instead of the JSON response. If I include the errorhandler in the same blueprint as the APIs, it works fine. How do I have a separate error handler blueprint?

like image 212
Mihika Avatar asked Oct 27 '25 15:10

Mihika


1 Answers

This answer explains your solution and works for me:

Can we have Flask error handlers in separate module

Looks like the only problem in your code is that you're using

@bp.errorhandler(404)

And you should be using

@bp.app_errorhandler(404)

like image 75
tgig Avatar answered Oct 30 '25 14:10

tgig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!