问题
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: 400httplib.UNAUTHORIZED: 401httplib.FORBIDDEN: 403httplib.NOT_FOUND: 404httplib.CONFLICT: 409httplib.GONE: 410httplib.PRECONDITION_FAILED: 412httplib.REQUEST_ENTITY_TOO_LARGE: 413
and these status codes will be mapped to other codes:
httplib.PAYMENT_REQUIRED: 402 mapped to 404httplib.METHOD_NOT_ALLOWED: 405 mapped to 501httplib.NOT_ACCEPTABLE: 406 mapped to 404httplib.PROXY_AUTHENTICATION_REQUIRED: 407 mapped to 404httplib.REQUEST_TIMEOUT: 408 mapped to 503httplib.LENGTH_REQUIRED: 411 mapped to 404httplib.REQUEST_URI_TOO_LONG: 414 mapped to 404httplib.UNSUPPORTED_MEDIA_TYPE: 415 mapped to 404httplib.REQUESTED_RANGE_NOT_SATISFIABLE: 416 mapped to 404httplib.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