pallets / flask

The Python micro framework for building web applications.

Home Page:https://flask.palletsprojects.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

@app.errorhandler() cannot be used in blueprint when debug=False

mengshun2022 opened this issue · comments

I want to customize an error type in Flask, and then use @app.errorhandler() in the main program to capture it. Then, I define a function raise_error to actively throw this exception. When debug=True is enabled at runtime, both the main and blueprint routes can be used normally in the interface function. However, when debug=False, only the main route can be used, and the blueprint route cannot capture it and reports a program error,I hope someone can help me take a look
There are two files in total(mains.py,aaa.py)

#python mains.py
from flask import jsonify, Flask
from typing import Union
app = Flask(__name__)

class CustomError(Exception):
    def __init__(self, message, status_code=500):
        try:
            self.message = message.__dict__
        except Exception as e:
            self.message = message
        self.status_code = status_code

def raise_error(msg: Union[dict, str], status: Union[int, str] = 500):
    raise CustomError(msg, status_code=status)

@app.route("/")
def home():
    raise_error("this is error")
    return {}

from aaa import router
app.register_blueprint(router)

@app.errorhandler(CustomError)
def handle_custom_exception(error: CustomError):
    response = jsonify({"code": error.status_code, "data": error.message})
    response.status = 20
    return response

if __name__ == "__main__":
    # app.run(host="0.0.0.0", port=7788, debug=True) #can in blueprint
    app.run(host="0.0.0.0", port=7788, debug=False)  # cannot in blueprint

#python aaa.py
from flask import Blueprint, jsonify

router = Blueprint("aaa", __name__, url_prefix="/aaa")

@router.get("/")
def aaa():
    from mains import raise_error
    print("is runing")
    raise_error("this is eror in blueprint")
    return jsonify({"data": "in blueprint"})
Flask==3.0.2
typing_extensions==4.10.0
python == 3.12.2
(my_flask) PS C:\Users\Administrator\Desktop\flask_project> & C:/ProgramData/miniconda3/envs/my_flask/python.exe c:/Users/Administrator/Desktop/flask_project/mains.py
 * Serving Flask app 'mains'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:7788
 * Running on http://192.168.3.69:7788
Press CTRL+C to quit
127.0.0.1 - - [05/Mar/2024 11:10:07] "GET / HTTP/1.1" 20 -
127.0.0.1 - - [05/Mar/2024 11:10:07] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [05/Mar/2024 11:10:12] "GET /aaa HTTP/1.1" 308 -
is runing
[2024-03-05 11:10:12,268] ERROR in app: Exception on /aaa/ [GET]
Traceback (most recent call last):
  File "C:\ProgramData\miniconda3\envs\my_flask\Lib\site-packages\flask\app.py", line 1463, in wsgi_app
    response = self.full_dispatch_request()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\ProgramData\miniconda3\envs\my_flask\Lib\site-packages\flask\app.py", line 872, in full_dispatch_request
    rv = self.handle_user_exception(e)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\ProgramData\miniconda3\envs\my_flask\Lib\site-packages\flask\app.py", line 870, in full_dispatch_request
    rv = self.dispatch_request()
         ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\ProgramData\miniconda3\envs\my_flask\Lib\site-packages\flask\app.py", line 855, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\Administrator\Desktop\flask_project\aaa.py", line 11, in aaa
    raise_error("this is eror in blueprint")
  File "c:\Users\Administrator\Desktop\flask_project\mains.py", line 17, in raise_error
    raise CustomError(msg, status_code=status)
mains.CustomError: this is eror in blueprint
127.0.0.1 - - [05/Mar/2024 11:10:12] "GET /aaa/ HTTP/1.1" 500 -
127.0.0.1 - - [05/Mar/2024 11:10:12] "GET /favicon.ico HTTP/1.1" 404 -