如何在单个地方处理烧瓶中的一般异常?

时间:2017-11-06 16:27:42

标签: python exception flask

我正在使用flask,这里举例说明我想做什么。我从烧瓶门户网站复制了代码。

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

运行应用

(py35) root@localhost:tmp root$ flask run
 * Serving Flask app "hello"
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

发送请求

root@localhost:~ root$ curl http://localhost:5000/
Hello, World!

我修改我的功能并更改它以引发错误。

@app.route('/')
    def hello_world():
        print(xyz)
        return 'Hello, World!'

当我尝试发送请求时,它失败了

[2017-11-06 10:22:13,625] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "/py35/lib/python3.5/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/py35/lib/python3.5/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/py35/lib/python3.5/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/nile2691/sbdev/StorageCenterUI/.tox/py35/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/py35/lib/python3.5/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "py35/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/private/tmp/hello.py", line 6, in hello_world
    print(xyz)
NameError: name 'xyz' is not defined

我可以在我的代码中添加try...except,但在实际代码中,它在很多地方,我不想在任何地方处理这个常规异常。

有没有像

这样的方式
try:
    process_flask_request()
except Exception as ex:
    # Log detail exception
    logger.exception(ex)
    return "Custome error message for all general exception"

通过此更改,而不是像下面那样得到一般错误

curl http://localhost:5000/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request.  Either the server is overloaded or there is an error in the application.</p>

我想返回正确的输出,并带有自定义错误消息。

1 个答案:

答案 0 :(得分:2)

您可以包含这样的错误处理程序,例如用于更好地显示示例中的内部服务器错误:

import traceback

(...some code...)

@app.errorhandler(500)
def internal_error(e):
    """
    handle internal errors nicely
    """
    tb = traceback.format_exc()
    return render_template('error.html',
                           error=e.message,
                           traceback=tb), 500

在模板中,您可以输出简短的错误消息,并且(如果您有用户管理,可能取决于用户权限)详细的堆栈跟踪。

正如您对问题的评论所述,您应该阅读文档以了解全貌。