flaskrestplus:如何捕捉所有异常并输出原点

2024-10-03 00:16:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图捕捉所有可能发生的异常,并将堆栈细节作为消息输出到FlaskRestPlus中。在

下面是一个示例,如果我引发自定义异常,如RootException,则可以使用它。但我没能让它与BaseException或任何其他可能起到包罗万象作用的东西一起工作。我也没有找到将堆栈(或原始错误消息)输出到消息体的方法。在

@api.errorhandler(RootException)
def handle_root_exception(error):
    return {'message': 'Here I want the original error message'}, 500

如有任何建议,我将不胜感激。文档似乎不太清楚:https://flask-restplus.readthedocs.io/en/stable/errors.html


Tags: 方法api消息示例message堆栈def错误
1条回答
网友
1楼 · 发布于 2024-10-03 00:16:48

要创建通用错误处理程序,可以使用:

@api.errorhandler(Exception)
def generic_exception_handler(e: Exception):

堆栈跟踪捕获

要自定义堆栈跟踪处理,请参见Python When I catch an exception, how do I get the type, file, and line number?。在

堆栈跟踪数据捕获示例

^{pr2}$

函数get_type_or_class_name是一个助手,它获取对象的类型名,或者在类的情况下,返回类名。在

def get_type_or_class_name(var: Any) -> str:
    if type(var).__name__ == 'type':
        return var.__name__
    else:
        return type(var).__name__

通常还提供HTTPException处理程序:

from werkzeug.exceptions import HTTPException

@api.errorhandler(HTTPException)
def http_exception_handler(e: HTTPException):

相关问题 更多 >