gpt4 book ai didi

javascript - Chrome 开发工具在拒绝的 promise 上暂停,即使我正在捕获它

转载 作者:行者123 更新时间:2023-12-02 21:43:32 24 4
gpt4 key购买 nike

我有以下 typescript 代码,我从 promise 创建函数中抛出同步错误:

function testExc(url: string): Promise<GLTF | undefined> {
try {
const promise: Promise<GLTF> = new Promise((resolve, reject) => {
throw Error('hi')
})
promise.catch((err) => { console.log(`Caught ${err}`) })
return promise
} catch (e) {
return Promise.resolve()
}
}

令我惊讶的是,这会在 Chrome 开发工具的 throw 行上触发“因 promise 拒绝而暂停”。我打开了“异常暂停”,并关闭了“捕获异常暂停”,因为我想了解未捕获的异常。

为什么会暂停?我通过两种方式捕获异常:使用 .catch 和围绕整个事件的 try/catch 。当我继续时,.catch 节按预期捕获它。

我在 Windows 10 上使用 Chrome 80.0.3987.116,使用 Typescript 3.7。

如果有帮助的话,转译的 JS 代码如下所示:

function testExc(url) {
try {
const promise = new Promise((resolve, reject) => {
throw Error('hi');
resolve(undefined);
});
promise.catch(err => {console.log(`Caught ${err}`);});
return promise;
}
catch (e) {
return Promise.resolve(undefined);
}
}

最佳答案

这个issue于 2015 年作为 chromium 的错误报告提出。以下是我在讨论中看到的一些相关言论:

The constructor callback is called synchronously before the ".catch()" code is executed, so at the time when the exception is thrown it is indeed uncaught. Later it becomes caught ... (aandrey@chromium.org)

Try-catch scope is static. At the time of throw, we know that it's going to be caught. (yangguo@chromium.org)

At the point the promise implementation checks and invokes the rejection handler can be a lot later. DevTools semantics require to break at the throw site though, to make any sense of "break on exception". (yangguo@chromium.org)

So I guess the scenario we are discussing is the case where the Promise is rejected in the constructor ... In this case, there is no chance to attach a reject handler yet. (yangguo@chromium.org)

长话短说,当您在 Promise 构造函数中抛出错误时,开发工具很难识别该错误稍后会被处理。

相反,在构造函数中处理它:

function testExc(url) {
return new Promise((resolve, reject) => {
try {
throw new Error('hi');
}
catch (e) {
console.log(`Caught ${e}`);
resolve();
}
})
}

关于javascript - Chrome 开发工具在拒绝的 promise 上暂停,即使我正在捕获它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60322164/

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