Skip to content

Instantly share code, notes, and snippets.

@twolfson
Created September 14, 2017 00:42
Show Gist options
  • Save twolfson/855a823cfbd62d4c7405a38105c23fd3 to your computer and use it in GitHub Desktop.
Save twolfson/855a823cfbd62d4c7405a38105c23fd3 to your computer and use it in GitHub Desktop.
Handling uncaught sync and async errors in AWS Lambda

AWS Lambda has nice safeguards for logging but not great handling for error reporting. I typically use Sentry but in this project, we're using Rollbar

Here's a setup to remove AWS Lambda's forceful exit on uncaught error and replace it with an error reporter to Rollbar:

// Load in our dependencies
const assert = require('assert');
const Rollbar = require('rollbar');

// Initialize our Rollbar handler
const rollbar = new Rollbar({
  accessToken: ROLLBAR_SERVER_ACCESS_TOKEN,
  enabled: ROLLBAR_ENABLED
});

// Add unexpected error handlers
// DEV: AWS Lambda's `uncaughtException` handler logs `err.stack` and exits forcefully
//   uncaughtException listeners = [function (err) { console.error(err.stack); process.exit(1); }]
//   We remove it so we can catch async errors and report them to Rollbar
assert.strictEqual(process.listeners('uncaughtException').length, 1);
assert.strictEqual(process.listeners('unhandledRejection').length, 0);
process.removeAllListeners('uncaughtException');
var reportErrorToRollbar = function (err) {
  console.error(err.stack);
  rollbar.error(err, function handleRollbarError (rollbarErr, rollbarInfo) {
    process.exit(1);
  });
};
process.on('uncaughtException', reportErrorToRollbar);
process.on('unhandledRejection', reportErrorToRollbar);
@twolfson
Copy link
Author

twolfson commented Aug 7, 2019

It's been 2 years since I wrote this. It's possible AWS changed their configuration =/

@acewert
Copy link

acewert commented Aug 8, 2019

I figured as much, but worth a shot. Thanks!

@scionaltera
Copy link

In the AWS Node 10 runtime it appears there's one unhandledRejection handler, so the assertion in this code fails.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment