使用flask-restful将错误消息传播到使用abort()方法,例如
abort(500, message="Fatal error: Pizza the Hutt was found dead earlier today
in the back seat of his stretched limo. Evidently, the notorious gangster
became locked in his car and ate himself to death.")这将生成以下json输出
{
"message": "Fatal error: Pizza the Hutt was found dead earlier today
in the back seat of his stretched limo. Evidently, the notorious gangster
became locked in his car and ate himself to death.",
"status": 500
}有没有办法用额外的成员定制json输出?例如:
{
"sub_code": 42,
"action": "redirect:#/Outer/Space"
"message": "You idiots! These are not them! You've captured their stunt doubles!",
"status": 500
}发布于 2014-02-08 07:19:17
人们倾向于过度使用abort(),而实际上生成自己的错误非常简单。您可以编写一个可以轻松生成自定义错误的函数,下面是一个与您的JSON匹配的函数:
def make_error(status_code, sub_code, message, action):
response = jsonify({
'status': status_code,
'sub_code': sub_code,
'message': message,
'action': action
})
response.status_code = status_code
return response然后,不是调用abort()执行以下操作:
@route('/')
def my_view_function():
# ...
if need_to_return_error:
return make_error(500, 42, 'You idiots!...', 'redirect...')
# ...发布于 2015-09-08 11:59:39
我没有50个名气来评论@dappiu,所以我只需要写一个新的答案,但它真的与
"Flask-RESTful设法提供了一种更干净的方式来处理错误“作为very poorly documented here
这是一个如此糟糕的文档,以至于我花了一段时间才弄清楚如何使用它。关键是您的自定义异常必须继承自flask_restful导入HTTPException。请注意,您不能使用Python Exception。
from flask_restful import HTTPException
class UserAlreadyExistsError(HTTPException):
pass
custom_errors = {
'UserAlreadyExistsError': {
'message': "A user with that username already exists.",
'status': 409,
}
}
api = Api(app, errors=custom_errors)Flask-RESTful团队在简化自定义异常处理方面做得很好,但文档毁掉了这项工作。
发布于 2017-07-07 18:25:48
正如@Miguel所示,通常你不应该使用异常,只需要返回一些错误响应即可。但是,有时您确实需要一种引发异常的中止机制。例如,这在过滤方法中可能很有用。请注意flask.abort接受一个Response对象(选中此gist):
from flask import abort, make_response, jsonify
response = make_response(jsonify(message="Message goes here"), 400)
abort(response)https://stackoverflow.com/questions/21638922
复制相似问题