1

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?

kochizufan
  • 2,120
  • 2
  • 30
  • 50
  • Assuming you are using API gateway to expose the Lambda functions, there is a good discussion here: http://stackoverflow.com/questions/31329495/is-there-a-way-to-change-the-http-status-codes-returned-by-amazon-api-gateway/31371862 – Rodrigo Murillo Jun 14 '16 at 22:34
  • 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 Jun 14 '16 at 22:49
  • Excellent! Looking forward to your findings. – Rodrigo Murillo Jun 14 '16 at 22:59

1 Answers1

1

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": ""
        }
    }
}