내용으로 건너뛰기

Sample Error handling and custom http status codes in Spring cloud function + Lambda + gateway

1

I am writing a lambda function using Spring cloud function where one of the function response is this

{
    "statusCode": 404,
    "body": {
        "message": "Account not found"
    }
}

Currently using the Payload version 2.0. But the api gateway does not react to the "statusCode" value in the response and just simply sends back the response from the lambda with 200 response code. Here is my template.yml file that I am currently using

AWSTemplateFormatVersion: '2010-09-09'
Description: Basic HTTP API with request and response parameter mapping
Resources:
  HTTPApi:
    Type: AWS::ApiGatewayV2::Api
    Properties:
      Name: Response-mapping
      ProtocolType: HTTP
  LambdaIntegration:
    Type: AWS::ApiGatewayV2::Integration
    Properties:
      ApiId: !Ref MyAPI
      IntegrationMethod: POST
      IntegrationType: AWS_PROXY
      IntegrationUri: !GetAtt MyFunction.Arn
      PayloadFormatVersion: '2.0'
      RequestParameters:
        "append:header.header1": "$context.requestId"
      ResponseParameters:
          - Source: "response.body.statusCode"
            Destination: "overwrite:statusCode"
  Route:
    Type: AWS::ApiGatewayV2::Route
    Properties:
      ApiId: !Ref HTTPApi
      RouteKey: 'GET /account'
      Target: !Join
        - /
        - - integrations
          - !Ref LambdaIntegration
  Stage:
    Type: AWS::ApiGatewayV2::Stage
    Properties:
      ApiId: !Ref HTTPApi
      AutoDeploy: true
      StageName: '$default'

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest
      Runtime: java11
      CodeUri: target/my-jar-aws.jar
      MemorySize: 512
      Timeout: 30
      Environment:
        Variables:
          spring.cloud.function.routing-expression: "@pathUtils.getEndpointName(payload)"


Outputs:
  InvokeURL:
    Value: !Sub https://${HTTPApi}.execute-api.${AWS::Region}.amazonaws.com

What exactly I am doing wrong here. I am stuck on this for a week now. Any help appreciated.

thanks

1개 답변
0

Hello,

Please refer to the following post https://repost.aws/questions/QUnI9Nj79iTWO76uK0E0DrSQ/sample-error-handling-and-custom-http-status-codes-in-spring-cloud-function-lambda-gateway

The ResponseParameter to map is $response.body.statusCode:

  LambdaIntegration:
    Type: AWS::ApiGatewayV2::Integration
    Properties:
      ApiId: !Ref MyAPI
      IntegrationMethod: POST
      IntegrationType: AWS_PROXY
      IntegrationUri: !GetAtt MyFunction.Arn
      PayloadFormatVersion: '2.0'
      RequestParameters:
        "append:header.header1": "$context.requestId"
      ResponseParameters:
          - Source: "$response.body.statusCode" # <------ notice the $
            Destination: "overwrite:statusCode"

Edit for some clarifications:

  1. you don't need to map manually the statusCode, the lambda can directly return the statusCode. exemple from the documentation
// bare minimum lambda function to return 404 response
exports.handler = async (event, context) => {
    console.log('returning code 404');
    return {
      "isBase64Encoded": false,
      "statusCode": 404,
      "body": "Hello from Lambda!",
      "headers": {
        "content-type": "application/json"
      }
    };
};
  1. you might want to check your lambda java code and try sending the same json from documentation which is known to be working.
  2. run a test directly from the lambda test page and see what is the response.
AWS

답변함 3년 전

  • I updated it to "$response.body.statusCode". It didn't work either. Not sure what other configurations that I can try

  • @rePost-User-3677295 I've updated my answer. the issue should come from the lambda itself

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

관련 콘텐츠