我正在使用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>


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

最佳答案

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

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


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

正如您对问题的评论中提到的那样,您应该阅读文档以获取完整信息。

关于python - 如何在单个位置处理 flask 中的一般异常?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47141503/

10-11 16:24