Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serverless offline custom error from API gateway with Lambda

Is there any way to return a custom error object and status code from API gateway? I am getting 200 status.

 var response = {
    status: 400,
    errors: [
       {
          code:   "226",
          message: "Password and password confirmation do not match."
        }
    ]
 }

context.done(JSON.stringify(response));
like image 316
Rubel hasan Avatar asked Apr 06 '26 00:04

Rubel hasan


2 Answers

If you want to respond with an error, you have to use the success callback with an error response construct.

If you are using the context.fail() callback, AWS will assume that the Lambda technically failed and respond with the default mapping present in your API Gateway.

Sample error response:

'use strict';

module.exports.hello = (event, context, callback) => {
  const response = {
    statusCode: 400,
    body: JSON.stringify({
      errors:[{
        code: "226",
        message:"Password confirmation do not match"
      }]
    }),
  };
  context.done(null, response);
};
like image 82
jens walter Avatar answered Apr 08 '26 13:04

jens walter


This way I can change API Gatway. I can manage my API response to using s-templates.json to adding this code base.

ValidationError":{
  "selectionPattern": ".*ValidationError.*",
  "statusCode": "400",
  "responseParameters": {
    "method.response.header.Access-Control-Allow-Headers": "'Content-
    Type,X-Amz-Date,Authorization,X-Api-Key,Cache-Control,Token'",
    "method.response.header.Access-Control-Allow-Methods": "'*'",
    "method.response.header.Access-Control-Allow-Origin": "'*'"
  },
  "responseModels": {},
  "responseTemplates": {
    "application/json": "$input.path('$.errorMessage')"
  }
}

This way I return my response with 400 statusCode and a valid message.

module.exports.handler = function(event, context) {
  const validationError={
    statsCode:"ValidationError",
    section:"Login",
    validationType:"emailConfirmation",
    message:"Email is not confirmed",
    otherInfo:"Would you like to get the email again?",
    client:"web|ios|android"
  }
  context.done(null, response);
};
like image 28
Rubel hasan Avatar answered Apr 08 '26 14:04

Rubel hasan