我想为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)
现在我觉得这种格式很吸引人,但是当出现异常时,我需要指定更多的参数。例如,当遇到ResourceDoesNotExist
时,我想要指定哪个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:
{'message': 'ResourceDoesNotExist: Resource MyModel 5 not found'}
这个可以正常工作,但我想使用Flask-restful的错误处理方式。