Setup Error Logging in Serverless

Link to chapter - https://serverless-stack.com/chapters/setup-error-logging-in-serverless.html

@jayair Thank you so much for the fantastic tutorials - I have learned so much going through these!

I was wondering about the error handling: it seems to me that errors (except for those from AWS directly re: Auth) are defaulted to 500 errors (via handler-lib.js). Would it not be useful to allow for specifying other response codes (i.e 404) where required?

[Update 15/04/2020]

Would this approach be advisable?

I extended the Error class and created an ApiError class with a statusCode property. In the API endpoint, throw new ApiError("Item not found", 404). In the handlerLib.js I create a statusCode variable defaulted to 500. If the Error has the name ApiError set the statusCode to the statusCode property from the error.

libs/ApiError.js:

export default class ApiError extends Error {
  constructor(message, code) {
    super(message, code);
    this.name = "ApiError";
    this.statusCode = code;
  }
}

libs/handlerLib.js:

...
.catch(e => {
      // Print debug messages
      console.log("Error retrieving note: ", { error: e });
      debug.flush(e);
      let statusCode = 500;
      if (e.name === "ApiError") {
        statusCode = e.statusCode;
      }
      return [statusCode, { error: e.message, errorType: e.name }];
    })
...

For successful Api responses, I return an object with body and statusCode properties which are then used in handlerLib.js too:

...
    // On success
   .then(responseBody => [responseBody.statusCode, responseBody.body])
...

Response object would look like this (get.js):

return {
  body: res.Item,
  statusCode: 201
}
2 Likes

Yup we are simply leaving it as 500 errors for now but you can extend it to return the error codes that you want. I would not simply pass the errors from DynamoDB along, it makes more sense to handle any sensitive data before returning it.

1 Like