2015-06-15 45 views
4

我有一個返回一瓶服務器HTTPErrors這樣:如何使用Bottle HTTPError在JSON中返回錯誤消息?

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

當我收到在瀏覽器這種反應,我希望能夠挑選出給出的錯誤信息。現在,我可以在響應的responseText字段中看到錯誤消息,但它隱藏在一個HTML字符串中,如果不需要,我不會解析它。

有沒有什麼辦法可以在Bottle中專門設置錯誤信息,所以我可以在瀏覽器中使用JSON來挑選它?

+0

不相關,但是...這是一個實際的錯誤?如果是這樣,它不應該是'400'狀態碼。應該返回一個'409衝突'恕我直言, – That1Guy

回答

4

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

纔剛剛開始瓶工作,但會推薦一些沿的線條更:

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) 

沒有運行的上方,預期錯誤,但你得到的要點。

5

我正在尋找一種類似的方式,將所有錯誤消息作爲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似乎相關。