使用默认错误处理程序处理瓶子/python错误

使用默认错误处理程序处理瓶子/python错误,python,error-handling,bottle,Python,Error Handling,Bottle,使用瓶/python,我试图获得更详细的错误处理。有一个页面描述了一种方法 ,但无法在我的项目中实现它 hayrabedian在上面提到的页面上的回答是有效的,但是为了获得更多错误情况的细节,Michael的代码有一些魅力。只有我测试过的任何变体都失败了。基本上我有(在较长的编码之外): 调用一个没有调用“默认错误处理程序”的无效页面,只调用带有“error:404 Not Found”的标准瓶子html错误页面。迈克尔的方法确实是最“正确”的方法。 这对我来说就像预期的那样(至少在python

使用瓶/python,我试图获得更详细的错误处理。有一个页面描述了一种方法 ,但无法在我的项目中实现它

hayrabedian在上面提到的页面上的回答是有效的,但是为了获得更多错误情况的细节,Michael的代码有一些魅力。只有我测试过的任何变体都失败了。基本上我有(在较长的编码之外):


调用一个没有调用“默认错误处理程序”的无效页面,只调用带有“error:404 Not Found”的标准瓶子html错误页面。

迈克尔的方法确实是最“正确”的方法。 这对我来说就像预期的那样(至少在python-3.6.6和瓶子-0.12.13中是这样):


现在,每个error()和abort()都是用于微服务设计的json解决方案

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

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

bottle.run(app)

在瓶子0.13-dev中会出现插件错误。
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)
def handle_404(error):
    return "404 Error Page not Found"

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

bottle.run(app)