可以为非常通用的基类注册错误处理程序,例如HTTPException 甚至Exception。但是,请注意,这些会比您预期的更多。
例如,HTTPException 的错误处理程序可能有助于将默认 HTML 错误页面转换为 JSON。但是,此处理程序将触发您不直接导致的事情,例如路由期间的 404 和 405 错误。请务必仔细设计您的处理程序,以免丢失有关 HTTP 错误的信息。
from flask import Flask, abort, jsonify, json
from werkzeug.exceptions import HTTPException
app = Flask('test')
app.config['JSON_SORT_KEYS'] = False
@app.errorhandler(HTTPException)
def handle_exception(e):
"""Return JSON instead of HTML for HTTP errors."""
# start with the correct headers and status code from the error
response = e.get_response()
# replace the body with JSON
response.data = json.dumps({
"error": {
"code": e.code,
"name": e.name,
"description": e.description,
}
})
print(response.data)
response.content_type = "application/json"
return response
@app.route('/')
def index():
abort(409)
@app.route('/aloha')
def aloha():
abort(400, "I'm not in the mood to talk!")
app.run(port=1234)
输出:
Exception 的错误处理程序对于更改所有错误(甚至未处理的错误)向用户呈现的方式似乎很有用。但是,这类似于 except Exception:在 Python 中,它将捕获 所有 否则未处理的错误,包括所有 HTTP 状态代码。
在大多数情况下,为更具体的异常注册处理程序会更安全。由于HTTPException 实例是有效的 WSGI 响应,因此您也可以直接传递它们。
from werkzeug.exceptions import HTTPException
@app.errorhandler(Exception)
def handle_exception(e):
# pass through HTTP errors
if isinstance(e, HTTPException):
return e
# now you're handling non-HTTP exceptions only
return render_template("500_generic.html", e=e), 500
错误处理程序仍然尊重异常类层次结构。如果您同时为HTTPException 和Exception 注册处理程序,则Exception 处理程序将不会处理HTTPException 子类,因为HTTPException 处理程序更具体。