I wanted an error from Lambda to be proper 500 error,
after doing a lot of research, came up with the below, that works:
On LAMBDA
For a good response, I am returning as below:
exports.handler = (event, context, callback) => {
// ..
var someData1 = {
data: {
httpStatusCode: 200,
details: [
{
prodId: "123",
prodName: "Product 1"
},
{
"more": "213",
"moreDetails": "Product 2"
}
]
}
};
return callback(null, someData1);
}
For a bad response, returning as below
exports.handler = (event, context, callback) => {
// ..
var someError1 = {
error: {
httpStatusCode: 500,
details: [
{
code: "ProductNotFound",
message: "Product not found in Cart",
description: "Product should be present after checkout, but not found in Cart",
source: "/data/attributes/product"
},
{
code: "PasswordConfirmPasswordDoesntMatch",
message: "Password and password confirmation do not match.",
description: "Password and password confirmation must match for registration to succeed.",
source: "/data/attributes/password",
}
]
}
};
return callback(new Error(JSON.stringify(someError1)));
}
On API Gateway
For a GET METHOD, say GET of /res1/service1:
Through Method Response > Add Response, added 3 responses:
- 200
- 300
- 400
Then,
Through 'Integration Response' > 'Add integration response', create a Regex for 400 errors (client error):
Lambda Error Regex .*"httpStatusCode":.*4.*
'Body Mapping Templates' > Add mapping template as:
Content-Type application/json
Template text box* $input.path('$.errorMessage')
Similarly, create a Regex for 500 errors (server error):
Lambda Error Regex .*"httpStatusCode":.*5.*
'Body Mapping Templates' > Add mapping template as:
Content-Type application/json
Template text box* $input.path('$.errorMessage')
Now, publish /res1/service1, hit the published URL, that is connected to above lambda
Used Advanced REST client (or Postman) chrome plugin, you will see proper http codes like server error (500) or 400, instead of 200 http response code for all requests where were given in "httpStatusCode".
From the 'Dashboard' of API, in API Gateway, we can see the http status codes like below: