Reputation: 24068
I have caught uncaughtException
event in my nodejs app to write a log when an exception occurred.
process.on('uncaughtException', (err) => {
log.warn('Caught exception. Exiting. error: ' + err + ', stack: ' + err.stack);
process.exit(1);
});
But, above handler is not called when an exception is thrown inside an express event handler.
someInvalidFunc(); //This causes the uncaughtException handler to get called.
app.all('/ping', function (req, res, next) {
someInvalidFunc(); //This doesn't cause the uncaughtException handler to get called.
res.status(200).json({status: 'OK'});
});
Even though the handler is not called, the error is printed to console.
Error: ReferenceError: someInvalidFunc is not defined
What is the reason for this? How can I catch all unhandled exceptions in the app?
Upvotes: 2
Views: 3702
Reputation: 119
If you are using express, the uncaughtException callback won't be even triggered as express provides a default error handler that catches error from the controller and sends 500 as a response.
You can override the error handler. This is explained in the docs: https://expressjs.com/en/guide/error-handling.html
Upvotes: 2