1
votes

I created Serverless framework's function by command below:

sls function create some/api

Then schelton code was created:

'use strict';

module.exports.handler = function(event, context, cb) {
  return cb({
    message: 'Go Serverless! Your Lambda function executed successfully!'
  });
};

and, response template is like below:

s-function.json

  "responses": {
    "400": {
      "statusCode": "400"
    },
    "default": {
      "statusCode": "200",
      "responseParameters": {},
      "responseModels": {
        "application/json;charset=UTF-8": "Empty"
      },
      "responseTemplates": {
        "application/json;charset=UTF-8": ""
      }
    }
  }

But, when I returned error object to callback function like cb(err, null), then error message was properly shown, but statusCode is 200.

If I changed to call callback function like cb("400", err), then statusCode properly returns 400, but response body is not good: {"errorMessage":"400"}.

Are there any good settings to show bot statusCode(Not only 400, but also 401,403,404,500...and so on) and error messages?

1
Assuming you are using API gateway to expose the Lambda functions, there is a good discussion here: stackoverflow.com/questions/31329495/… - Rodrigo M
Thank you! It's not I'm imagined, but with it, I can solve my problem by another way. I'll summarize the result later. - kochizufan
Excellent! Looking forward to your findings. - Rodrigo M

1 Answers

1
votes

I use following response template. If the message returned from the lambda function matches the selectionPattern specified in the response template, it will return the correct status code.

"responseTemplate": {
    "400": {
        "selectionPattern": "^\\[BadRequest\\].*",
        "statusCode": "400"
    },
    "401": {
        "selectionPattern": "^\\[Unauthorized\\].*",
        "statusCode": "401"
    },
    "403": {
        "selectionPattern": "^\\[Forbidden\\].*",
        "statusCode": "403"
    },
    "404": {
        "selectionPattern": "^\\[NotFound\\].*",
        "statusCode": "404"
    },
    "409": {
        "selectionPattern": "^\\[Conflict\\].*",
        "statusCode": "409"
    },
    "500": {
        "selectionPattern": "^\\[Process exited|ServerError\\].*",
        "statusCode": "500"
    },
    "504": {
        "selectionPattern": "^\\[Task timed out\\].*",
        "statusCode": "504"
    },
    "default": {
        "statusCode": "200",
        "responseParameters": {},
        "responseModels": {},
        "responseTemplates": {
            "application/json": ""
        }
    }
}