How to capture the errors in node.js using uncaughtException

How to capture the errors in node.js using uncaughtException

Problem

In my application i want to create own module to capture my application error using uncaughtException.If i create uncaughtException in same module means its capturing errors but if i create that uncaughtException in separate module.Then call that module means its not capturing erros.Can anyone help me to fix this issue.

module1.js

   var errorModule=require('./module2');
   var err = new Error('Something went terribly wrong');
   errorModule.captureError(err);

module2.js

  module.exports.captureError=function(err){

     process.on('uncaughtException', function(err) {

       console.log(err);

   });



 }
Problem courtesy of: sachin

Solution

Try this:

// module1.js
var errorModule=require('./module2');
errorModule.captureErrors();    
throw Error('Something went terribly wrong');

// module2.js
module.exports.captureErrors = function() {
  process.on('uncaughtException', function(err) {
    console.log('an error occurred', err);
  });
};

A few things to notice:

  • process.on('uncaughtException', ...) installs an event handler to catch uncaught exceptions; your code tries to pass an error to it, but that seems to defeat what you’re writing (‘to capture my application error using uncaughtException’);
  • Uncaught exceptions are errors which are thrown (throw Error(...));

If you want the code in your module1 to work, module2 needs to look like this:

module.exports.captureError = function(err) {
  console.log(err);
};

But that has nothing to do with uncaughtException.

Solution courtesy of: robertklep

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *