Bottle/Python默认错误处理程序的错误处理

3

我正在使用Bottle/Python尝试实现更详细的错误处理。有一个页面描述了一种方法如何使用Bottle HTTPError返回JSON格式的错误信息?,但是我无法在我的项目中实施它。

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'不会被调用,只会显示标准的bottle html错误页面,内容为"Error: 404 Not Found"。

2个回答

1

迈克尔的方法确实是最“正确”的方法。 这对我来说按预期工作了(至少在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格式的


1

微服务设计解决方案

def handle_404(error):
    return "404 Error Page not Found"

app = bottle.Bottle()
app.error_handler = {
    404: handle_404
}

bottle.run(app)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接