我正在处理Node.js服务端应用程序,我的情况是我想将引发异常返回给调用方(确实调用了该函数),我做了两种情况,一种在回调外部,另一种在回调内部,父母也有尝试抓块。
概念:throw(业务功能)-> throw(业务功能)-> try&catch
外部回调正常工作。在回调内部没有将异常返回给父级。
我想要这种情况,因为我要向父级抛出异常并停止完成功能,而Java,C ++,C和.NET中都存在这种情况。
那么,为什么这种情况对我不起作用?
我的示例在这里有2种不同的情况:
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());
}
}
发生异常是因为您引发了错误。如果您想将错误返回给调用者,则需要在回调中提供它。将错误作为参数添加到回调中。
通常,回调模式是 callback(error, result);
callback(new Error(ex.toString())); // ignore result param
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句