如何使用 Bottle HTTPError return JSON 中的错误消息?

How to return error messages in JSON with Bottle HTTPError?

我有一个 bottle 服务器 returns HTTPErrors 是这样的:

return HTTPError(400, "Object already exists with that name")

当我在浏览器中收到此响应时,我希望能够找出给出的错误消息。现在我可以在响应的 responseText 字段中看到错误消息,但它隐藏在一个 HTML 字符串中,如果不需要,我宁愿不解析它。

有什么方法可以专门在 Bottle 中设置错误消息,以便我可以在浏览器的 JSON 中挑选出来?

HTTPError 使用预定义的 HTML 模板构建响应正文。除了使用 HTTPError,您还可以使用 response 以及适当的状态代码和正文。

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, abort

@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 似乎相关。