Gracefully log errors in an AWS Lambda

Hi,

I currenlty have several NodeJS Lambda functions deployed on AWS.
I use to report errors using console.error as it allows me to not stop everything and treat other events in the same batch for example.

I’d like Sentry to alert me when something is wrong on my Lambdas, but without throwing an exception as it totally stops the execution.

What is the way you recommand for such cases ? I can use some Sentry SDK functions instead of calling console.error if needed.

Best regards
Max

1 Like

Stumbled across this today, too, and this is my solution:

Part 1: custom captureException

This method is a wrapper around the Sentry method, because apparently we have to also call flush() manually and also we want to console.error(), too.

import { captureException as SentryCaptureException, flush } from '@sentry/serverless';

/**
 * Capture an exception and send it to our error tracking software (currently: Sentry).
 *
 * Also, log it so that we can see it in the lambda logs, too.
 *
 * @param exception
 */
export async function captureException(exception: any): Promise<void> {
  console.error(exception);
  SentryCaptureException(exception);

  /*
   * Flushing appears to be necessary to guarantee sending the exception before the event loop ends.
   * This is unfortunate, as it can delay the overall execution by the amount of milliseconds in the worst case.
   * Therefore we want to log how long the real delay was, and also keep it capped at a reasonable amount.
   */
  const monitoringLabel = `captureException(): flush()`;
  console.time(monitoringLabel);
  await flush(200);
  console.timeEnd(monitoringLabel);
}

Part 2: Catch exceptions and capture them

In our application (handler) code, we now just catch the exceptions (instead of letting them break the handler execution) and then capture them:

    try {
        const foo = doSomething();
    } catch (error) {
        await captureException(error);
        return;
    }

All of the Sentry methods are included in the Sentry Lambda Layer, so no need to install additional dependencies if using that :slight_smile: