我已经创建了一个基本的Flask应用程序,并为特定的自定义异常类型注册了一个自定义错误处理程序。但是,当抛出此异常类型并向上传递堆栈时,Flask不使用指定的自定义错误处理程序。在
我创建了第二个具有基本异常类型的错误处理程序,它成功地捕获了错误。基本异常处理程序的存在不会影响自定义错误处理程序捕获错误的能力,如果基本处理程序不存在,则错误会一直冒泡到默认的Flask 500页面。在
我还完成了print(srv.error_handler_spec)
,似乎错误处理程序正在成功注册。在
这是srv.py
的主要部分,这是我的Flask应用程序的入口点
from flask import Flask, request
from flask import jsonify
srv = Flask(__name__)
class APIError(Exception):
def __init__(self, message, status_code=500):
Exception.__init__(self)
self.message = message
self.status_code = status_code
def log_error(self):
logging.error(f"API error: {self.to_json()}")
def to_dict(self):
return {"message": self.message, "status_code": self.status_code}
@srv.errorhandler(Exception)
def exception_handler(e: Exception):
response = jsonify(
{"message": f"unhandled exception encountered", "status_code": 500}
)
logging.error(f"unhandled exception encountered. type: {e.__class__}")
response.status_code = 500
return response
@srv.errorhandler(APIError)
def api_error_handler(e: APIError):
response = jsonify(e.to_dict())
response.status_code = e.status_code
return response
print(srv.error_handler_spec)
@srv.route("/", methods=["GET"])
def hello_world():
return "hello world"
@srv.route("/error", methods=["GET"])
def error():
raise APIError("generic error", status_code=400)
这是Flask卷取时的日志输出/error
从日志行ERROR:root:unhandled exception encountered. type: <class 'srv.APIError'>
可以看出,它使用的是通用的Exception
处理程序,而不是{
预期的行为是,Flask将转而使用自定义错误处理程序,根本不打印任何日志行。在
对于记录,curl
的结果与返回响应的通用错误处理程序一致。对于泛型处理程序打击更具体的处理程序,这绝对不是问题。(尽管根据Flask的文件,这也是错误的)。在
什么给予?在
我找到了一个解决方法,即将
APIError
定义放入一个单独的Python文件中,并将其导入srv.py
。在失败的原因是
isinstance()
不能正常工作。引发的异常具有类型srv.APIError
,但它所针对的类型是__main__.APIError
,这不是同一类型。在这不是由于来自另一个模块的类型隐藏,因为将错误类型名更改为
StupidError
会产生相同的结果。在不过,我还是不知道为什么会这样。:/
相关问题 更多 >
编程相关推荐