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!

1

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

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 nodejs.org/api/process.html#process_event_uncaughtexception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.