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);
I figured as much, but worth a shot. Thanks!