使用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.")
{ "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 }
解决方法
人们倾向于过度使用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...') # ...