首页 > 解决方案 > 如何从内部函数调用返回错误?

问题描述

小JS问题。我在函数中有以下代码report

this.httpClient(reqConfig).catch(function (error) {
    console.log("here");
    return new Error('Failed with' + error);
});

我怎样才能Error退货report?据我了解,目前它只是返回Errorcatch然后继续运行report

标签: javascript

解决方案


要使承诺catch返回拒绝,您需要抛出错误或返回被拒绝的承诺:

throw new Error('Failed with ' + error);

或者

return Promise.reject(new Error('Failed with ' + error));

然后要报告(按原样)该错误,它必须report返回由. 例如,如果是一个函数,则结果来自. 如果不是,则返回该结果:catchcatchreportasyncawaitcatch

return this.httpClient(reqConfig).catch(function (error) {
    console.log("here");t
    throw new Error('Failed with' + error);
});

为清楚起见:您不能从该回调中report 引发错误catch,因为report在该回调运行之前已经返回。(虽然 ifreport是一个async函数,但您可以编写逻辑,就好像它真的在抛出错误一样。)


推荐阅读