Amazon web services 如何更改API网关响应

Amazon web services 如何更改API网关响应,amazon-web-services,api,amazon-cloudformation,aws-api-gateway,serverless,Amazon Web Services,Api,Amazon Cloudformation,Aws Api Gateway,Serverless,我有一个aws ApiGateway来验证我的令牌并将请求传递给lambda 当lambda出现错误时,APIGateway响应为 { "statusCode": 500, "error": "Internal Server Error", "message": "..." } 但是如果我没有传递我的令牌,APIGateway会返回我 { "message": "Unauthorized" } 在《邮递员》中,我有状态码:401 我希望它是怎样的: {

我有一个aws ApiGateway来验证我的令牌并将请求传递给lambda

当lambda出现错误时,APIGateway响应为

{
    "statusCode": 500,
    "error": "Internal Server Error",
    "message": "..."
}
但是如果我没有传递我的令牌,APIGateway会返回我

{
    "message": "Unauthorized"
}
在《邮递员》中,我有状态码:401

我希望它是怎样的:

{
    "statusCode": 401,
    "error": "Unauthorized"
}
我使用serverless.yml部署:

functions:
  index:
    handler: dist/index.handler
    events:
    - http:
        cors: true
        path: '/'
        method: any
        authorizer:
          type: COGNITO_USER_POOLS
          authorizerId:
            Ref: ApiGatewayAuthorizer
请告诉我如何更改serverless.yml以将“Unauthorized”错误更改为第三个代码示例中的错误。

尝试实现以下操作: :

允许获得如下响应:

{
  "success":false,
  "message":"Custom Deny Message"
}

您可以通过修改网关响应来实现这一点

  • 转到AWS管理控制台中的API网关
  • 选择您的API
  • 单击左侧的“网关响应”
  • 在网关响应列表中选择“未经授权”
  • 在响应模板中选择“应用程序/json”,然后单击“编辑”
  • 根据您的要求更新响应模板正文
  • 单击“保存”
  • 重新部署API

  • 添加到@svladimirrc后,即使您没有自定义授权程序,它也会起作用,只需确保您已将API网关的正确名称配置为链接到:

    resources:
      Resources:
        ApiGatewayRestApi:
          Type: AWS::ApiGateway::RestApi
          Properties:
            Name: ${self:provider.stage}-${self:service}
        InvalidApiKeyGatewayResponse:
          Type: 'AWS::ApiGateway::GatewayResponse'
          Properties:
            RestApiId: 
              Ref: 'ApiGatewayRestApi'
            ResponseType: INVALID_API_KEY
            ResponseTemplates:
              application/json: "{\"success\":false,\"message\":\"Invalid API key\"}"
            StatusCode: '401'