1
votes

I use serverless to implement Lambda and Api gateway. When I implement Error Handling, below code always get 502 bad gateway.

handler.js

module.exports.hello = (event, context, callback) => {
  const response = {
      statusCode: 400,
      headers: {
        "Content-Type" : "application/json"
      },
      body: JSON.stringify({
        "status": "error",
        "message": "Missing Params"
      })
    };
    callback(response);
};

CloudWatch do log error.

{
    "errorMessage": "[object Object]"
}

I code this way by following the method "Custom error object serialization" in below AWS blog. Ref

2

2 Answers

5
votes

I change callback first parms to null and work fine. Ref

module.exports.hello = (event, context, callback) => {
  const response = {
      statusCode: 400,
      headers: {
        "Content-Type" : "application/json"
      },
      body: JSON.stringify({
        "status": "error",
        "message": "Missing Params"
      })
    };
    callback(null, response);
};
0
votes

This is a common pattern in Node.js and its called Error-First Callbacks.

Basically, if you pass a first argument into your callback, it will be considered and handled as an Error.

As you mentioned, once you put a callback(null, response);, it all worked as expected, since the first argument is null.