javascript - 如何从内部函数调用返回错误?
问题描述
小JS问题。我在函数中有以下代码report
:
this.httpClient(reqConfig).catch(function (error) {
console.log("here");
return new Error('Failed with' + error);
});
我怎样才能Error
退货report
?据我了解,目前它只是返回Error
,catch
然后继续运行report
。
解决方案
要使承诺catch
返回拒绝,您需要抛出错误或返回被拒绝的承诺:
throw new Error('Failed with ' + error);
或者
return Promise.reject(new Error('Failed with ' + error));
然后要报告(按原样)该错误,它必须report
返回由. 例如,如果是一个函数,则结果来自. 如果不是,则返回该结果:catch
catch
report
async
await
catch
return this.httpClient(reqConfig).catch(function (error) {
console.log("here");t
throw new Error('Failed with' + error);
});
为清楚起见:您不能从该回调中report
引发错误catch
,因为report
在该回调运行之前已经返回。(虽然 ifreport
是一个async
函数,但您可以编写逻辑,就好像它真的在抛出错误一样。)
推荐阅读
- java - switch 语句在这里是否合适,采用枚举?
- android - 如何配置 Flutter 的 showModalBottomSheet 开/关动画?
- xml - 通过 BASH while 循环构造语法正确的 JSON 文件
- reactjs - 如何对无状态 Material-ui 组件进行单元测试?功能无法从外部访问
- bash - Bash for 循环跳过数组的第一个元素
- c# - 尝试从 gridview 更新时出现死锁错误
- angular - angular ng serve 命令抛出错误:发生未处理的异常:项目不存在
- linux - 尝试运行 bash 脚本时出现“找不到命令”
- python-3.x - 如何使用 pycharm 在生产模式下发布应用程序?
- automation - Cypress 获取属性值并存储在变量中