对于bottle/python,我试图获得更详细的错误处理。有一个描述方法How to return error messages in JSON with Bottle HTTPError?的页面,但不能在我的项目中实现它。
Ara.hayrabedian在提到的页面上的答案是有效的,但希望获得更多关于错误情况的细节,Michael的代码有一些魅力。只有我测试过的所有变体都失败了。基本上我有(在一个较长的编码中):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bottle import Bottle, run, static_file, view, template, \
get, post, request, debug
from bottle import route, response, error
import json
app = Bottle()
#class JSONErrorBottle(bottle.Bottle): ### just an not working alternative!?
class JSONErrorBottle(Bottle):
def default_error_handler(app, res):
bottle.response.content_type = 'application/json'
print("XXXXXXX " + json.dumps(dict(error=res.body, status_code=res.status_code)))
return json.dumps(dict(error=res.body, status_code=res.status_code))
app.install(JSONErrorBottle)
def main():
app.run(host = prefs['server'], port = prefs['port'], reloader=False)
if __name__ == '__main__':
rcode = main()调用没有调用'default_error_handler‘的无效页面,只调用标准的瓶子html错误页面" error : 404not Found“
发布于 2018-08-15 02:46:10
迈克尔的方式确实是最“正确”的方式。这对我来说是正常的(至少在python-3.6.6和bottle-0.12.13中是这样的):
from bottle import Bottle, run, abort
import bottle, json
class JSONErrorBottle(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))
app = JSONErrorBottle()
@app.route('/hello')
def hello():
return dict(message = "Hello World!")
@app.route('/err')
def err():
abort(401, 'My Err')
run(app, host='0.0.0.0', port=8080, debug=True)现在,每个error()和abort()都是json
发布于 2021-02-22 17:53:58
微服务设计解决方案
def handle_404(error):
return "404 Error Page not Found"
app = bottle.Bottle()
app.error_handler = {
404: handle_404
}
bottle.run(app)https://stackoverflow.com/questions/42576609
复制相似问题