【问题标题】:Best practice to avoid throwing exceptions on endpoints?避免在端点上抛出异常的最佳实践?
【发布时间】:2013-09-21 08:21:11
【问题描述】:

我正在使用 Bottle 公开 HTTP 端点——仅输出 JSON。

当前抛出的错误:{'error': %s, 'error_message': %s, 'status_code': #}。

所以在我所有的端点装饰函数中:

try:
    someObj = <stuff>
except <MyCustomErrors> as e:
    response.status = e.response.pop('status_code', 500)
    return e.response

response.status = someObj.response.pop('status_code', 200)

return someObj.response

但我可以轻松地避免一起使用异常,从而生成更简洁的 + DRYer 端点代码并减少开销。

但也有缺点;其他开发人员需要至少阅读或运行一次代码以了解输出格式。

文档可以在这里使用;但是,这整个设置是不好的做法吗?

【问题讨论】:

    标签: python exception exception-handling try-catch endpoint


    【解决方案1】:

    与此同时,我写了这个可怜的替代品:

    # Not a decorator because I can't work out how to give `@route(apply=)` func args
    def error_else_response(init_with):
        try:
            result = init_with(**request.query)
        except <CustomError> as e:
            response.status = e.msg.pop('status_code')
            return e.msg
    
        response.status = result.response.pop('status_code')
    
        return result.response
    
    
    @route('/augment')
    def augment():
        return error_else_response(<CustomClass>)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 2011-06-13
      • 2011-12-24
      • 1970-01-01
      • 2010-09-06
      相关资源
      最近更新 更多