Mihika
Mihika

Reputation: 535

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?

Upvotes: 4

Views: 1657

Answers (1)

tgig
tgig

Reputation: 163

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)

Upvotes: 5

Related Questions