Nodejs throw exception

would the below code satisfy your requirement

'use strict';
var  inherits =require('util').inherits;
//Parent
function factoryController(n){
     this.name=n;
 }
 //parent prototype function
 factoryController.prototype.create = function (type) {
     var retVal="";
     try {
     throw new Error('An error occurred'); 
      retVal=this.name+' is a '+ type;
     }
     catch(e){
         retVal=e.toString();
     }
     return retVal;

}
 function subsidaryController(name) {
       // Call parent constructor 
        factoryController.call(this, name);

    }
inherits(subsidaryController,factoryController);
// Additional member functions 
 subsidaryController.prototype.fn = function (locations) {
     var retVal="";
     try {
          throw new Error('Another error occurred'); 
          retVal='Having branches in' + locations;
     }
     catch(e){
         retVal=e.toString();
     }
     return retVal;
 }   
 let fc = new subsidaryController('ABC Factory');
console.log(fc.create('Manufacturer' ));
console.log(fc.fn('Europe and Asia'));

Exceptions occurs because you are throwing the errors. If you rather want to return the error to the caller, you need to provide it in the callback. Add the error as parameter to the callback.

Usually the callback pattern is callback(error, result);

callback(new Error(ex.toString())); // ignore result param

Error handling in Nodejs

Tags:

Node.Js