1

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!

Alon
  • 10,381
  • 23
  • 88
  • 152
  • 2
    Possible duplicate of [Node.js Best Practice Exception Handling](http://stackoverflow.com/questions/7310521/node-js-best-practice-exception-handling) – Blue Nov 06 '16 at 13:31

1 Answers1

1

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/

Rakesh Kumar
  • 2,705
  • 1
  • 19
  • 33
  • 2
    This is one way of doing it but I don't think it is solid advice considering OP's situation. Please see `Warning: Using 'uncaughtException' correctly` https://nodejs.org/api/process.html#process_event_uncaughtexception – brk Nov 06 '16 at 14:11