endpoints.ServiceException子类返回400状态代码而不是409

  发布于 2023-01-20 21:28

在用于异常处理的Cloud Endpoints 文档中,建议对类进行子endpoints.ServiceException类化以提供http_status409 Conflict错误的自定义.这回答另一个问题表明,一些支持的状态代码得到由谷歌的基础设施,其他状态代码映射,但409不是映射的状态代码之一.

使用ConflictException文档中的类:

import endpoints
import httplib

class ConflictException(endpoints.ServiceException):
    """Conflict exception that is mapped to a 409 response."""
    http_status = httplib.CONFLICT

当我提出ConflictException:

@endpoints.method(request_message=apimodels.ClientMessage,
                  response_message=apimodels.ClientMessage,
                  name='insert',
                  path='/clients',
                  http_method='POST'
)
def insert(self, request):
    client = models.Client.get_by_id(request.client_code)
    if client:
        raise ConflictException('Entity with the id "%s" exists.' % request.client_code)

    ...

我收到400 Bad Request作为回复:

400 Bad Request

Content-Length:  220
Content-Type:  application/json
Date:  Thu, 27 Feb 2014 16:11:36 GMT
Server:  Development/2.0

{
 "error": {
  "code": 400,
  "errors": [
   {
    "domain": "global",
    "message": "Entity with the id \"FOO\" exists.",
    "reason": "badRequest"
   }
  ],
  "message": "Entity with the id \"FOO\" exists."
 }
}

我在本地dev_appserver上获得相同的400响应代码并部署到App Engine(在1.9.0上).进入App Engine ProtoRPC代码,以下行似乎将所有remote.ApplicationError类型映射到400状态代码.

如果我更新endpoints.apiserving._ERROR_NAME_MAPdict以添加我的自定义ConflictException类,我可以成功返回409:

import endpoints
import httplib
from endpoints.apiserving import _ERROR_NAME_MAP

class ConflictException(endpoints.ServiceException):
    """Conflict exception that is mapped to a 409 response."""
    http_status = httplib.CONFLICT


_ERROR_NAME_MAP[httplib.responses[ConflictException.http_status]] = ConflictException

这是实现endpoints.ServiceException子类的正确方法吗?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有