Alon Alon - 1 month ago 8
Javascript Question

Catching errors in Node.js

In my Node.js app, I want to catch all the unhandled errors and write them into a log.

Currently I wrap every edge-point code with a try/catch block, but it's a lot of work. I need a way to catch all the errors in one place, like the Global.asax application_error in ASP.Net, so instead of that:

function a(){
try{
var wrong = 3 / 0;
} catch(err){
console.log(err);
}
}

function b(){
try{
var wrong = 3 / 0;
} catch(err){
console.log(err);
}
}

function c(){
try{
var wrong = 3 / 0;
} catch(err){
console.log(err);
}
}


I will only have something like that:

function a() {
var wrong = 3 / 0;
}

function b() {
var wrong = 3 / 0;
}

function c() {
var wrong = 3 / 0;
}

function errorHandler(err) {
console.log(err);
}


Any help will be profoundly appreciated!

Answer

You can use uncaught exception to catch all the error from one place.

process.on('uncaughtException', function (err) {
  console.error((new Date).toUTCString() + ' uncaughtException:', err.message)
  console.error(err.stack)
  process.exit(1)
})

https://shapeshed.com/uncaught-exceptions-in-node/