Nodejs抛出异常

Muh*_*iri 12 node.js

我正在研究Nodejs服务端应用程序,我的情况是我想返回抛出一个异常给调用者(谁调用了函数),我做了两个案例,一个在回调之外,另一个在回调内部,父母也尝试捕获块.

概念:throw(业务功能) - > throw(业务功能) - > try&catch

回调外部正常工作.回调内部没有将异常返回给父级.

我想要这个场景,因为我希望向父节点抛出一个异常并停止完成这些函数,这些存在于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());
}
Run Code Online (Sandbox Code Playgroud)

}

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());
}
Run Code Online (Sandbox Code Playgroud)

}

Tap*_*boy 7

发生异常是因为您引发了错误。如果您想将错误返回给调用者,则需要在回调中提供它。将错误作为参数添加到回调中。

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

callback(new Error(ex.toString())); // ignore result param
Run Code Online (Sandbox Code Playgroud)

Node.js中的错误处理