在Flask中显示Exception的最佳方法是什么?

问题描述 投票:0回答:2

我是Flask的新手,我正在尝试在python中显示Built-In Exceptions,但我似乎无法将它们展示在我的最后。

注意:

set FLASK_DEBUG = 0

码:

def do_something:
    try:
        doing_something()
    except Exception as err:
        return f"{err}"

期望:

  • 它将显示一个内置异常: KeyError异常 IndexError NameError 等等。

现实:

  • 它将返回对最终用户更不明确的代码行。

也:

  • 调试模式为ON时,我没有看到错误,但如果我公开打开它,那就不是我想要做的事情了
python flask
2个回答
1
投票

Flask为您提供了一个功能,使您能够在整个app中注册错误处理程序;你可以做一些如下所示的事情:

def handle_exceptions(e):
    # Log exception in your logs
    # get traceback and sys exception info and log as required   
    # app.logger.error(getattr(e, 'description', str(e)))

    # Print traceback

    # return your response using getattr(e, 'code', 500) etc. 

# Exception is used to catch all exceptions
app.register_error_handler(Exception, handle_exceptions)

老实说,这是要走的路。 - 以werkzeug.exceptions.HTTPException中的结构为例,是一个坚实的基础。

拥有一个统一的异常处理程序,可以使您的Exception处理,可视化和日志记录标准化,这将使您的生活更加美好。 :)


1
投票

试试这个:

def do_something:
    try:
        doing_something()
    except Exception as err:
        return f"{err.__class__.__name__}: {err}"
© www.soinside.com 2019 - 2024. All rights reserved.