【问题标题】:How can one subclass endpoints.ServiceException?如何继承endpoints.ServiceException?
【发布时间】:2013-05-14 07:17:26
【问题描述】:

文档在https://developers.google.com/appengine/docs/python/endpoints/exceptions 中提到了“子类化端点。ServiceException”。但是,子类不能真正表达字符串消息、“状态”和 http 代码之外的任何内容。

为了让任何应用程序具有更智能的异常处理,错误需要携带的不止于此。

如何子类化异常类,提供自定义消息/状态?

【问题讨论】:

    标签: google-app-engine python-2.7 google-cloud-endpoints


    【解决方案1】:

    目前还没有办法扩展payload,但是可以自定义状态码。

    正如在endpoints.api_exceptions 中针对400 错误所做的那样:

    import httplib
    class BadRequestException(ServiceException):
      """Bad request exception that is mapped to a 400 response."""
      http_status = httplib.BAD_REQUEST
    

    当前支持的错误状态代码列表(截至 2013 年 5 月 8 日)是:

    • httplib.BAD_REQUEST: 400
    • httplib.UNAUTHORIZED:401
    • httplib.FORBIDDEN:403
    • httplib.NOT_FOUND:404
    • httplib.CONFLICT: 409
    • httplib.GONE:410
    • httplib.PRECONDITION_FAILED:412
    • httplib.REQUEST_ENTITY_TOO_LARGE:413

    这些状态码会映射到其他码:

    • httplib.PAYMENT_REQUIRED: 402 映射到 404
    • httplib.METHOD_NOT_ALLOWED: 405 映射到 501
    • httplib.NOT_ACCEPTABLE: 406 映射到 404
    • httplib.PROXY_AUTHENTICATION_REQUIRED: 407 映射到 404
    • httplib.REQUEST_TIMEOUT: 408 映射到 503
    • httplib.LENGTH_REQUIRED: 411 映射到 404
    • httplib.REQUEST_URI_TOO_LONG: 414 映射到 404
    • httplib.UNSUPPORTED_MEDIA_TYPE: 415 映射到 404
    • httplib.REQUESTED_RANGE_NOT_SATISFIABLE: 416 映射到 404
    • httplib.EXPECTATION_FAILED: 417 映射到 404

    此外,如果您的响应是 message_types.VoidMessage 对象,您将能够发送 204 无内容响应 (httplib.NO_CONTENT)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多