【问题标题】:Flask RestPlus: how to catch all exceptions and output the original errorFlask RestPlus:如何捕获所有异常并输出原始错误
【发布时间】:2019-11-30 22:45:44
【问题描述】:

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

【问题讨论】:

    标签: python flask error-handling flask-restplus


    【解决方案1】:

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

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

    【讨论】:

    • @Nickpick 查看带有get_type_or_class_name定义的更新答案。
    • 这在调试模式下效果很好,但如果它在生产模式下似乎不起作用(即烧瓶不在调试或使用 iis 运行)。有什么建议我能做些什么吗?
    猜你喜欢
    • 2020-09-04
    • 2018-06-17
    • 2015-12-18
    • 2011-08-20
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    相关资源
    最近更新 更多