Skip to main content
 首页 » 编程设计

python之Flask RestPlus : how to catch all exceptions and output the original error

2024年11月24日8Leo_wl

我正在 try catch 所有可能发生的异常,并将堆栈详细信息作为消息输出到 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

请您参考如下方法:

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

@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? .

示例堆栈跟踪数据捕获

import sys 
 
... 
 
@api.errorhandler(Exception) 
def generic_exception_handler(e: Exception): 
    exc_type, exc_value, exc_traceback = sys.exc_info() 
 
    if exc_traceback: 
        traceback_details = { 
            'filename': exc_traceback.tb_frame.f_code.co_filename, 
            'lineno': exc_traceback.tb_lineno, 
            'name': exc_traceback.tb_frame.f_code.co_name, 
            'type': get_type_or_class_name(exc_type), 
            'message': str(exc_value), 
        } 
        return {'message': traceback_details['message']}, 500 
    else: 
        return {'message': 'Internal Server Error'}, 500 

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):