How can one subclass endpoints.ServiceException?

假如想象 提交于 2019-12-08 10:36:22

问题


The documentation mentions "subclassing endpoints.ServiceException" at https://developers.google.com/appengine/docs/python/endpoints/exceptions. However, subclasses can't really express anything beyond a string message, "state" and http code.

For any application to have smarter exception handling, errors need to carry more than this.

How can one subclass the exception class, providing a custom message/state?


回答1:


Currently, there is no way to extend the payload, but you can customize the status code.

As is done in endpoints.api_exceptions for a 400 error:

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

The current list (as of 5/8/2013) of status codes supported for errors are:

  • 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

and these status codes will be mapped to other codes:

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

In addition if your response is a message_types.VoidMessage object, you will be able to send 204 no content response (httplib.NO_CONTENT).



来源:https://stackoverflow.com/questions/16399254/how-can-one-subclass-endpoints-serviceexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!