您可以使用
@app.errorhandler(Exception):
演示(HTTPException检查可确保保留状态码):
from flask import Flask, abort, jsonifyfrom werkzeug.exceptions import HTTPExceptionapp = Flask('test')@app.errorhandler(Exception)def handle_error(e): pre = 500 if isinstance(e, HTTPException): pre = e.pre return jsonify(error=str(e)), pre@app.route('/')def index(): abort(409)app.run(port=1234)输出:
$ http get http://127.0.0.1:1234/HTTP/1.0 409 CONFLICTContent-Length: 31Content-Type: application/jsonDate: Sun, 29 Mar 2015 17:06:54 GMTServer: Werkzeug/0.10.1 Python/3.4.3{ "error": "409: Conflict"}$ http get http://127.0.0.1:1234/notfoundHTTP/1.0 404 NOT FOUNDContent-Length: 32Content-Type: application/jsonDate: Sun, 29 Mar 2015 17:06:58 GMTServer: Werkzeug/0.10.1 Python/3.4.3{ "error": "404: Not Found"}如果您还想覆盖Flask的默认HTML异常(以便它们也返回JSON),请在以下内容之前添加以下内容
app.run:
from werkzeug.exceptions import default_exceptionsfor ex in default_exceptions: app.register_error_handler(ex, handle_error)
对于较旧的Flask版本(<= 0.10.1,即当前的任何非git / master版本),将以下代码添加到您的应用程序中以显式注册HTTP错误:
from werkzeug import HTTP_STATUS_CODESfor pre in HTTP_STATUS_CODES: app.register_error_handler(pre, handle_error)



