Nodejs抛出exception

我正在使用Nodejs服务端应用程序,我的情况是我想要返回抛出exception的调用者(谁调用函数),我做了两个情况,一个callback之外,另一个callback,父母也尝试catch块。

概念:throw(商业function) – > throw(商业function) – > try&catch

callback之外工作正常。 callback内部没有将exception返回给父级。

我想这个场景,因为我正在寻找抛出一个exception的父,并停止完成的function,这存在于Java,C + +,C和.NET中。

那么为什么这个场景不适合我?

我的例子有两种不同的情况:

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()); } 

}

发生exception是因为您正在抛出错误。 如果您希望将错误返回给调用者,则需要在callback中提供该错误。 将错误作为参数添加到callback中。

通常callback模式是callback(error, result);

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

在Nodejs中处理错误