在Flask中显示异常的最好方法是什么?

2024-06-12 10:37:19 发布

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

我是一个在烧瓶里的新手,我正在尝试用python显示Built-In Exceptions,但我似乎无法在我的端部显示它们。在

注:

set FLASK_DEBUG = 0

代码:

^{pr2}$

期望值:

  • 它将显示一个内置异常:
    • 错误键
    • 索引器
    • 名称错误
    • 等等

现实:

  • 它将返回不起作用的代码行,这对最终用户来说更加模糊。在

同时:

  • 当调试模式打开时,我可以看到错误,但如果我公开打开它们,我不想这样做

Tags: 代码indebug名称flask烧瓶错误内置
2条回答

试试这个:

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

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)

老实说,这才是正道。-以{{CD3}}中发现的结构为例,是一个坚实的基础。在

拥有一个统一的异常处理程序来标准化您的Exception处理、可视化和日志记录将使您的生活稍微好一点。:)

相关问题 更多 >