您可以使用@app.errorhandler(Exception)
:
Demo(HTTPException检查确保状态代码被保留):
from flask import Flask, abort, jsonify
from werkzeug.exceptions import HTTPException
app = Flask('test')
@app.errorhandler(Exception)
def handle_error(e):
code = 500
if isinstance(e, HTTPException):
code = e.code
return jsonify(error=str(e)), code
@app.route('/')
def index():
abort(409)
app.run(port=1234)
输出:
$ http get http://127.0.0.1:1234/
HTTP/1.0 409 CONFLICT
Content-Length: 31
Content-Type: application/json
Date: Sun, 29 Mar 2015 17:06:54 GMT
Server: Werkzeug/0.10.1 Python/3.4.3
{
"error": "409: Conflict"
}
$ http get http://127.0.0.1:1234/notfound
HTTP/1.0 404 NOT FOUND
Content-Length: 32
Content-Type: application/json
Date: Sun, 29 Mar 2015 17:06:58 GMT
Server: Werkzeug/0.10.1 Python/3.4.3
{
"error": "404: Not Found"
}
如果你想覆盖 Flask 默认的 HTML 异常(使它们也返回 JSON),请在 app.run
之前添加以下内容:
from werkzeug.exceptions import default_exceptions
for ex in default_exceptions:
app.register_error_handler(ex, handle_error)
对于旧版本的 Flask(小于等于0.10.1,即当前任何非Git/Master版本),请将以下代码添加到您的应用程序中以显式注册HTTP错误:
对于旧版Flask (<=0.10.1,即当前任何非git/master版本),可以通过在应用程序中加入下面的代码来明确地注册HTTP错误:
from werkzeug import HTTP_STATUS_CODES
for code in HTTP_STATUS_CODES:
app.register_error_handler(code, handle_error)
Exception
不再起作用了。这是一个巨大的退步。他们为什么要改变它? - Houman