gpt4 book ai didi

python - 使用 default_error_handler 处理 Bottle/python 错误

转载 作者:行者123 更新时间:2023-12-03 07:45:15 24 4
gpt4 key购买 nike

我试图通过 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”的无效页面,只是带有“错误:404 未找到”的标准 bottle html 错误页面

最佳答案

微服务设计解决方案

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

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

bottle.run(app)

关于python - 使用 default_error_handler 处理 Bottle/python 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42576609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com