简体   繁体   English

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

[英]What's the best way to display Exception in Flask?

I'm a newbie in Flask and I am trying to display the Built-In Exceptions in python but I can't seem to have them display on my end. 我是Flask的新手,并且尝试显示python中的内置异常 ,但是我似乎无法在它们的末端显示它们。

NOTE: 注意:

set FLASK_DEBUG = 0

CODE: 码:

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

Expectation: 期望:

  • It will display one of the built-in exceptions: 它将显示内置异常之一:
    • KeyError KeyError
    • IndexError IndexError
    • NameError NameError
    • Etc. 等等。

Reality: 现实:

  • It will return the line of code that didn't worked which is more ambiguous to the end user. 它将返回无效的代码行,这对最终用户来说是更加模棱两可的。

Also: 也:

  • I have no problem seeing the errors when the debug mode is ON but that's not something that I want to do if I open them in public 在调试模式为ON时我没有看到错误的问题,但是如果我在公共场所打开它们,那不是我想要做的事情

Try with this: 试试这个:

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

Flask supplies you with a function that enables you to register an error handler throughout your entire app ; Flask为您提供了一个功能,使您可以在整个app程序中注册错误处理app you can do something as shown below: 您可以执行以下操作:

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)

In my honest opinion, this is the way to go. 我诚实地认为,这是要走的路。 - Following the structure found in werkzeug.exceptions.HTTPException as an example is a solid foundation. -以werkzeug.exceptions.HTTPException的结构为例,这是一个坚实的基础。

Having a unified exception handler that will standardise your Exception handling, visualisation and logging will make your life a tad better. 拥有一个统一的异常处理程序,它将使您的Exception处理,可视化和日志记录标准化,从而使您的生活更美好。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM