【问题标题】:Bottle/python error handling with default_error_handler使用 default_error_handler 处理 Bottle/python 错误
【发布时间】:2017-07-23 10:18:34
【问题描述】:

对于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 Not Found”的标准瓶子html错误页面

【问题讨论】:

    标签: python error-handling bottle


    【解决方案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

    【讨论】:

      【解决方案2】:

      微服务设计解决方案

      def handle_404(error):
          return "404 Error Page not Found"
      
      app = bottle.Bottle()
      app.error_handler = {
          404: handle_404
      }
      
      bottle.run(app)
      

      【讨论】:

      • Bottle 0.13-dev 中会出现插件错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-27
      相关资源
      最近更新 更多