Flask Restful API统一异常处理(abort方法)

对于后端API,遵循Restful定义,我们的返回值在异常时候也一定是要json格式的,如何来处理呢?话不多说,主要涉及到两片代码

自定义abort函数

首先,我们定义abort函数,用来处理中断

# -*- coding: utf-8 -*-
"""
error.py
error handdler
"""
from flask import jsonify
from werkzeug.http import HTTP_STATUS_CODES
from itpms.common import return_code	# 这个return_code自己根据需要定义,也可以直接用HTTP CODE
from itpms.api.v1.order import api as order_api


def api_abort(code, message=None, **kwargs):
    if message is None:
        message = HTTP_STATUS_CODES.get(code, '')

    response = jsonify(message=message, **kwargs)
    return response,code


def invalid_token():
    response, code = api_abort(return_code.Unauthorized, message='invalid token')
    return response, code


def token_missing():
    response, code = api_abort(return_code.Unauthorized, message='token missed')
    return response, code


def token_expired():
    response, code = api_abort(return_code.Forbidden, message='token expired')
    return response, code


class ValidationError(ValueError):
    pass

# 简单列了一些,别的类型自己可以根据需要扩展补充

@order_api.errorhandler(ValidationError)
def validation_error(e):
    return api_abort(400, e.args[0])

然后在app启动处注册一个错误处理器,为捕获到主要的一些错误调用abort作中断处理

# -*- coding: utf-8 -*-
"""
main.py
"""
def register_errors(app):
    @app.errorhandler(400)
    def bad_request(e):
        return api_abort(return_code.Unauthorized)

    @app.errorhandler(403)
    def forbidden(e):
        return api_abort(return_code.Forbidden)

    @app.errorhandler(404)
    def database_not_found_error_handler(e):
        return api_abort(return_code.NotFound)

    @app.errorhandler(405)
    def method_not_allowed(e):
        return api_abort(return_code.Illegalmethod, message='The method is not allowed for the requested URL.')

    @app.errorhandler(500)
    def internal_server_error(e):
        return api_abort(return_code.InternalServerError, message='An internal server error occurred.')

    # The default_error_handler function as written above will not return any response if the Flask application
    # is running in DEBUG mode.
    @app.errorhandler
    def default_error_handler(e):
        message = 'An unhandled exception occurred. -> {}'.format(str(e))
        logger.error(message)

        # if not settings.FLASK_DEBUG:
        return api_abort(return_code.InternalServerError, message=message)

#然后在生成app时注册它
def create_app():
    app = Flask(__name__)
	...
	register_errors(app)

然后就可以啦,对于全局错误(比如200、404、500)可以由上述的错误处理器进行统一处理,而对于本地错误(自定义错误)也可以直接调用abort函数来抛出错误中断,或者直接用提前定义好的中断函数处理:

# -*- coding: utf-8 -*-
"""
test.py
"""
from app.common.error import api_abort, invalid_token

api_abort(4001, '参数错误')

invalid_token()

你可能感兴趣的:(python,flask)