Python 如何在JSON中使用BLACK HTTPError返回错误消息?
我有一个瓶子服务器,它返回HTTPErrors,如下所示:Python 如何在JSON中使用BLACK HTTPError返回错误消息?,python,json,bottle,Python,Json,Bottle,我有一个瓶子服务器,它返回HTTPErrors,如下所示: return HTTPError(400, "Object already exists with that name") 当我在浏览器中收到此响应时,我希望能够找出给出的错误消息。现在,我可以在响应的responseText字段中看到错误消息,但它隐藏在一个HTML字符串中,如果不需要的话,我宁愿不解析它 是否有任何方法可以专门在瓶子中设置错误消息,以便在浏览器中用JSON将其识别出来?HTTPError使用预定义的HTML模板构建
return HTTPError(400, "Object already exists with that name")
当我在浏览器中收到此响应时,我希望能够找出给出的错误消息。现在,我可以在响应的responseText
字段中看到错误消息,但它隐藏在一个HTML字符串中,如果不需要的话,我宁愿不解析它
是否有任何方法可以专门在瓶子中设置错误消息,以便在浏览器中用JSON将其识别出来?
HTTPError
使用预定义的HTML模板构建响应主体。您可以将response
与适当的状态代码和正文一起使用,而不是使用HTTPError
import json
from bottle import run, route, response
@route('/text')
def get_text():
response.status = 400
return 'Object already exists with that name'
@route('/json')
def get_json():
response.status = 400
response.content_type = 'application/json'
return json.dumps({'error': 'Object already exists with that name'})
# Start bottle server.
run(host='0.0.0.0', port=8070, debug=True)
刚开始使用瓶子,但会推荐一些更符合以下原则的产品:
import json
from bottle import route, response, error
@route('/text')
def get_text():
abort(400, 'object already exists with that name')
# note you can add in whatever other error numbers
# you want, haven't found a catch-all yet
# may also be @application.error(400)
@error(400) #might be @application.error in some usages i think.
def json_error(error):
"""for some reason bottle don't deal with
dicts returned the same way it does in view methods.
"""
error_data = {
'error_message': error.body
}
response.content_type = 'application/json'
return json.dumps(error_data)
没有运行上面的操作,因此可能会出现错误,但您已经了解了要点。我正在寻找类似的方法,将所有错误消息作为JSON响应处理。上述解决方案的问题是,他们没有以一种好的、通用的方式来处理任何可能的弹出错误,而不仅仅是定义的400等。最干净的解决方案是,覆盖默认错误,然后使用自定义瓶子对象:
class JSONErrorBottle(bottle.Bottle):
def default_error_handler(self, res):
bottle.response.content_type = 'application/json'
return json.dumps(dict(error=res.body, status_code=res.status_code))
传递的
res
参数还有一些关于抛出错误的属性,这些属性可能会返回,请参阅代码以获取默认模板。尤其是.status
、.exception
和.traceback
似乎相关。不相关,但……这是实际错误吗?如果是这样,它不应该是400
状态代码。应该返回一个409冲突
,如果您描述了如何使用这样的类,这将非常有用。仅仅声明类本身似乎没有任何作用-如何告诉瓶子使用它作为默认的错误处理程序?