我想为Flask-restful API定义自定义错误处理。
在文档中建议的方法在这里是要做到以下几点:
errors = { 'UserAlreadyExistsError': { 'message': "A user with that username already exists.", 'status': 409, }, 'ResourceDoesNotExist': { 'message': "A resource with that ID no longer exists.", 'status': 410, 'extra': "Any extra information you want.", }, } app = Flask(__name__) api = flask_restful.Api(app, errors=errors)
现在,我发现这种格式非常吸引人,但是当发生某些异常时,我需要指定更多参数。例如,遇到时·,我要指定id不存在的内容。
目前,我正在执行以下操作:
app = Flask(__name__) api = flask_restful.Api(app) class APIException(Exception): def __init__(self, code, message): self._code = code self._message = message @property def code(self): return self._code @property def message(self): return self._message def __str__(self): return self.__class__.__name__ + ': ' + self.message class ResourceDoesNotExist(APIException): """Custom exception when resource is not found.""" def __init__(self, model_name, id): message = 'Resource {} {} not found'.format(model_name.title(), id) super(ResourceNotFound, self).__init__(404, message) class MyResource(Resource): def get(self, id): try: model = MyModel.get(id) if not model: raise ResourceNotFound(MyModel.__name__, id) except APIException as e: abort(e.code, str(e))
当使用不存在的ID调用时,MyResource将返回以下JSON:
MyResource
{'message': 'ResourceDoesNotExist: Resource MyModel 5 not found'}
这工作正常,但我想改用Flask-restful错误处理。
Flask-restful
根据文档
Flask-RESTful将在Flask-RESTful路由上发生的任何400或500错误上调用handle_error()函数,而将其他路由保留下来。
你可以利用它来实现所需的功能。唯一的缺点是必须创建自定义Api。
class CustomApi(flask_restful.Api): def handle_error(self, e): flask_restful.abort(e.code, str(e))
如果保留定义的异常,则发生异常时,你将获得与
class MyResource(Resource): def get(self, id): try: model = MyModel.get(id) if not model: raise ResourceNotFound(MyModel.__name__, id) except APIException as e: abort(e.code, str(e))