简体   繁体   English

在烧瓶中,我应该手动捕获视图中的所有可能错误吗?

[英]In flask, should i manually catch all possible error in views?

I'm new on Flask, when writing view, i wander if all errors should be catched. 我是Flask的新手,在编写视图时,如果应该捕获所有错误,我会徘徊。 If i do so, most of view code should be wrappered with try... except. 如果我这样做,大多数视图代码应该包含try ... except。 I think it's not graceful. 我认为这不是优雅的。

for example. 例如。

@app.route('/')
def index():
    try:
        API.do()
    except:
        abort(503)

Should i code like this? 我应该像这样编码吗? If not, will the service crash(uwsgi+lnmp)? 如果没有,服务会崩溃(uwsgi + lnmp)吗?

You only catch what you can handle. 你只能抓住你能处理的东西。 The word "handle" means "do something useful with" not merely "print a message and die". “句柄”一词意味着“做一些有用的事情”而不仅仅是“打印消息而死”。 The print-and-die is already handled by the exception mechanism and probably does it better than you will. 打印和骰子已经由异常机制处理,并且可能比你更好。

For example, this is not handling an exception usefully: 例如,这不是有用的处理异常:

denominator = 0
try:
    y = x / denominator
except ZeroDivisionError:
    abort(503)

There is nothing useful you can do, and the abort is redundant as that's what uncaught exceptions will cause to happen anyway. 你无能为力, abort是多余的,因为无论如何,未被捕获的异常将导致发生。 Here is an example of a useful handling: 以下是有用处理的示例:

try:
    config_file = open('private_config')
except IOError:
    config_file = open('default_config_that_should_always_be_there')

but note that if the second open fails, there is nothing useful to do so it will travel up the call stack and possibly halt the program. 但请注意,如果第二次打开失败,没有任何用处,它会向上移动调用堆栈并可能暂停程序。 What you should never do is have a bare except: because it hides information about what faulted where. 你永远不应该做的是except:因为它隐藏了有关故障的信息。 This will result in much head scratching when you get a defect report of "all it said was 503" and you have no idea what went wrong in API.do() . 当你得到“所有它说的是503”的缺陷报告并且你不知道API.do()API.do()什么问题时,这会导致很多人API.do()

Try / except blocks that can't do any useful handling clutter up the code and visually bury the main flow of execution. 尝试/除了无法进行任何有用处理的块会使代码混乱并在视觉上掩盖主要的执行流程。 Languages without exceptions force you to check every call for an error return if only to generate an error return yourself. 没有异常的语言会强制您检查每次调用错误返回,如果只是为了生成错误返回自己。 Exceptions exist in part to get rid of that code noise. 部分存在例外以消除代码噪声。

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

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