通过 errorhandler 处理全局异常,统一返回json格式的数据

# -*- coding: utf-8 -*-
from flask import Flask, jsonify

app = Flask(__name__)


@app.route("/getInfo")
def get_info():
    """获取用户信息
    """
    data = {
        "code": 0,
        "msg": "ok",
        "data": {
            "name": "Tom",
        }
    }

    # l = 1/0  # 触发异常
    return jsonify(data)


@app.errorhandler(Exception)
def error_handler(e):
    """
    全局异常捕获

    """
    data = {
        "code": -1,
        "msg": str(e),
        "data": None
    }

    return jsonify(data)


if __name__ == '__main__':
    app.run(debug=True)

正确返回

{
	code: 0,
	msg: "ok"
	data: {
		name: "Tom"
	}
}

程序报错返回

{
	code: -1,
	data: null,
	msg: "division by zero"
}