javascript - 围绕 Javascript 中的“嵌套”try/catch 语句感到困惑
问题描述
本质上,我有一个包含 try/catch 的异步函数,该函数调用另一个也包含 try catch 的异步函数,我对如何正确实现我正在做的事情有点困惑。一些“伪代码”显示了我当前的实现:
const main = async () => {
try {
const test = await secondFunc();
console.log(test);
} catch(err) {
console.log('Found an error!');
console.log(err);
}
const secondFunc = async () => {
try {
await performSomeRequestExample();
} catch(err) {
if (err.x === 'x') {
doSomething();
} else {
//********
throw err;
//********
}
}
所以我想要做的是让throw(err)
(被星号包围)被catch
in捕获,main()
其中也将调用 the console.log('Found an error!')
,但目前发生的是错误是从抛出的secondFunc()
,catch
inmain()
永远不会被击中,我得到一个未处理的承诺拒绝。
关于我做错了什么的任何指导?
解决方案
我的建议是尽量减少使用 try/catch,除非绝对必要。使用async
函数(或任何返回Promise
对象的函数),您通常可以通过不必担心 try/catch 块来简化事情,除非您需要针对某些错误执行特定操作。你也可以使用.catch
而不是 try/catch 块来使事情更容易阅读。
例如你上面的代码可以这样写:
const main = async () => {
const test = await secondFunc().catch(err => {
console.log("Found an error from secondFunc!", err);
throw err; // if you want to send it along to main's caller
});
if (test) {
console.log("Test", test);
}
};
const secondFunc = () => {
return performSomeRequestExample().catch(err => {
if (err.x === "x") {
doSomething();
} else {
throw err;
}
});
};
const performSomeRequestExample = () => Promise.reject("bad");
main().then(
() => console.log("worked"),
err => console.log("failed from main", err)
);
我们secondFunc
不需要使用async
,因为我们可以只返回从返回的承诺performSomeRequestExample
并处理.catch
.
推荐阅读
- php - 我们应该总是在 MySQL 和 php 中使用准备好的语句,还是什么时候使用它们?
- php - 我如何告诉 PHP 在评论中获取和发布用户名?
- mysql - 如何在关系表(laravel)中自动插入用户ID?
- c# - c# 如何为按钮列表创建事件列表?
- ironpython - 如何明确告诉用户等到脚本在 Spotfire 中完成
- angular - 如何在 FormArray 中设置 FormControl 的值
- php - 从特定源字段将数据从表发送到另一个表
- python - 如何避免 GUI 和程序其余部分之间的循环依赖?
- java - 不能在 JSP 中使用 Wildfly 数据源
- angular-material - 在反应形式中使用 Mat 选项组