首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用default_error_handler处理Bottle/python错误

使用default_error_handler处理Bottle/python错误
EN

Stack Overflow用户
提问于 2017-03-03 18:36:45
回答 2查看 2.3K关注 0票数 2

对于bottle/python,我试图获得更详细的错误处理。有一个描述方法How to return error messages in JSON with Bottle HTTPError?的页面,但不能在我的项目中实现它。

Ara.hayrabedian在提到的页面上的答案是有效的,但希望获得更多关于错误情况的细节,Michael的代码有一些魅力。只有我测试过的所有变体都失败了。基本上我有(在一个较长的编码中):

代码语言:javascript
复制
#!/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“

EN

回答 2

Stack Overflow用户

发布于 2018-08-15 02:46:10

迈克尔的方式确实是最“正确”的方式。这对我来说是正常的(至少在python-3.6.6和bottle-0.12.13中是这样的):

代码语言:javascript
复制
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

票数 0
EN

Stack Overflow用户

发布于 2021-02-22 17:53:58

微服务设计解决方案

代码语言:javascript
复制
def handle_404(error):
    return "404 Error Page not Found"

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

bottle.run(app)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42576609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档