I'm working on Nodejs service-side application, my case is that i want to return the throw an exception to the caller(who did call the function), i did two cases, one outside the callback, and the another inside the callback, also the parent has try catch blocks.
concept : throw(Business function)-->throw (Business function) -->try & catch
Outside the callback is working correctly. Inside the callback didn't return the exception to the parent.
I want to to this scenario,because I'm looking to throw an exception to the parent and stop completion the functions, and this's exist in Java, C++, C and .NET.
So why this scenario is not working with me ?!
My example here with 2 different cases :
FactoryController.prototype.create = function (callback) {
//The throw is working, and the exception is returned.
throw new Error('An error occurred'); //outside callback
try {
this.check(function (check_result) {
callback(check_result);
});
} catch (ex) {
throw new Error(ex.toString());
}
}
FactoryController.prototype.create = function (callback) {
try {
this.check(function (check_result) {
//The throw is not working on this case to return the exception to the caller(parent)
throw new Error('An error occurred'); //inside callback
});
} catch (ex) {
throw new Error(ex.toString());
}
}
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
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With