如何用Bottle HTTPError在JSON中返回错误信息?[英] How to return error messages in JSON with Bottle HTTPError?

本文是小编为大家收集整理的关于如何用Bottle HTTPError在JSON中返回错误信息?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个返回httperrors的瓶服务器:

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

当我在浏览器中收到此响应时,我希望能够挑选给给出的错误消息.现在,我可以在响应的responseText字段中看到错误消息,但是它被埋在HTML字符串中,如果不需要,我不想解析它.

有什么办法可以在瓶子中专门设置错误消息,以便我可以在浏览器中的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)

其他推荐答案

我正在寻找一种类似的方式,将所有错误消息处理为JSON响应.上述解决方案的问题是,他们不会以良好且通用的方式进行操作,即处理任何可能的弹出错误,而不仅仅是定义的400等.imho最清洁的解决方案是覆盖默认错误,并且然后使用自定义瓶子对象:

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

其他推荐答案

只是开始使用瓶子,但会推荐更多的东西:

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)

没有运行上述错误,所以要期待错误,但是您会得到要点.

本文地址:https://www.itbaoku.cn/post/1509145.html

问题描述

I have a bottle server that returns HTTPErrors as such:

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

When I receive this response in the browser, I'd like to be able to pick out the error message given. As it is right now I can see the error message in the response's responseText field, but it's buried in an HTML string that I'd rather not parse if I don't have to.

Is there any way I can specifically set the error message in Bottle so I can pick it out in JSON in the browser?

推荐答案

HTTPError uses a predefined HTML template to build the body of the response. Instead of using HTTPError you can use response with the appropriate status code and body.

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)

其他推荐答案

I was looking for a similar way, to handle all error messages as JSON responses. The problem with the above solution is, that they don't do it in a nice and generic way, i.e. to handle any possible popping error, not just a defined 400 etc. Imho the cleanest solution is, to override the default error, and then work with a custom bottle object:

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))

The passed res argument has some more attributes about the thrown error, which may be returned, see the code for the default template for that. Especially .status, .exception and .traceback seem relevant.

其他推荐答案

only just started working with bottle but would recommend something more along the lines of:

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)

didn't run the above so expect mistakes, but you get the gist.