gpt4 book ai didi

javascript - javascript中嵌套函数的try/catch问题

转载 作者:行者123 更新时间:2023-12-05 00:35:39 28 4
gpt4 key购买 nike

我有一个像下面这样的场景:

try {
top();
} catch(e) {
console.log(e);
}

function top() {
nestedFunc1();
}

function nestedFunc1() {
nestedFunc2();
}

function nestedFunc2() {
// this function throws an exception.
}

每当在我的 Node 脚本中引发异常时,我的 catch block 都不会被执行。这是预期的行为还是我在这里遗漏了一些东西。

最佳答案

使用上面的代码,nestedFunc2 的异常肯定会被那个try捕获/catch堵塞。

我怀疑您真正拥有的是异步回调中的异常:

try {
someNodeAPIFunction((err, result) => {
// Exception thrown here
});
} catch (e) {
console.log(e);
}

如果是这样,那么是的, try 是完全正常的。/ catch没有捕获异常,因为该代码已经完成运行。回调称为 稍后 .唯一能捕捉到异常的是 someNodeAPIFunction 中的代码。调用回调。

这是回调 API 难以使用的原因之一。

在任何最新版本的 Node.js 中,您都可以使用 async/ await简化事情。 Node.js 现在提供了一些支持 Promise 的 API 函数(特别是 fs.promises 模块),还提供了 promisify 实用函数,可用于将标准 Node.js 回调样式函数转换为返回 Promise 的函数。因此,例如,与上述:
const someNodeAPIFunctionPromisified = util.promisify(someNodeAPIFunction);

然后,在 async功能,你可以这样做:
try {
const result = await someNodeAPIFunctionPromisified();
// Exception thrown here
} catch (e) {
console.log(e);
}

...并且异常会被捕获,因为 async即使在处理异步结果时,函数也可以让您正确处理代码的逻辑流程。

更多关于 async功能 on MDN .

关于javascript - javascript中嵌套函数的try/catch问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59716534/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com