I create a Python/Flask application with the following code in main.py:
import json
from flask import Flask, jsonify
from werkzeug.exceptions import HTTPException, default_exceptions
from blueprints import test
def create_app(config_filename=None) -> Flask:
"""Application factory function
"""
app = Flask(__name__, instance_relative_config=True)
if config_filename:
app.config.from_pyfile(config_filename)
for exc in default_exceptions:
app.register_error_handler(exc, handle_error)
register_blueprints(app)
return app
def handle_error(error):
code = 500
if isinstance(error, HTTPException):
code = error.code
return jsonify(error='error', code=code)
def register_blueprints(app: Flask):
"""Register blueprints
"""
app.register_blueprint(test.bp)
def handle_exception(ex: HTTPException):
"""Return JSON instead of HTML for HTTP errors."""
# start with the correct headers and status code from the error
response = ex.get_response()
# replace the body with JSON
response.data = json.dumps({
"code": ex.code,
"error": ex.name,
"message": ex.description,
})
response.content_type = "application/json"
return response
if __name__ == '__main__':
main_app = create_app()
main_app.run(host='0.0.0.0', port=80, debug=True, threaded=False)
and the source code of the test.py blueprint is:
from flask import Blueprint, jsonify, request
from werkzeug.exceptions import HTTPException, default_exceptions
bp = Blueprint('blabla', __name__)
@bp.route('/blabla', methods=['POST'])
def blabla():
"""Test blueprint
"""
raise MyException()
class MyException(HTTPException):
code = 409
name = 'My Exception'
description = 'My Exception'
unfortunately when i execute the endpoint, the exception is not handled by the method, defined in the main.py
I even decided and tried to register error handlers in the blueprint, but the result is the same - the exception is not handled by the methods.
Here is the modified test.py
from flask import Blueprint, jsonify, request
from werkzeug.exceptions import HTTPException, default_exceptions
bp = Blueprint('blabla', __name__)
@bp.errorhandler(409)
def error_handler(e):
return handle_error(e)
@bp.route('/blabla', methods=['POST'])
def blabla():
"""Test blueprint
"""
raise MyException()
def handle_error(error):
code = 500
if isinstance(error, HTTPException):
code = error.code
return jsonify(error='error', code=code)
class MyException(HTTPException):
code = 409
name = 'My Exception'
description = 'My Exception'
Can someone tell me what is my error? Why the exception is not handled by the error methods?