gpt4 book ai didi

javascript - 为什么在异步函数中捕获后仍然抛出异常?

转载 作者:行者123 更新时间:2023-12-01 16:09:45 30 4
gpt4 key购买 nike

当捕获异常时,其余代码仍然执行。

function bad(){
//throw new Error('I am an exception')
return Promise.reject("I am an exception")
}

(
async function (){
let msg = await bad().catch( e=>console.log("This is an error: " + e))
console.log("I want to stop before executing this line ")
}
)()

我正在尝试以这种方式捕获异常而不是 try catch

我的第一个问题是如何在捕获到错误后阻止代码到达其余代码。

第二个问题是,如果我将 Promise reject 替换为注释掉的 throw error,抛出的异常错误将不会被捕获,这是为什么呢?

最佳答案

因为您正在使用 catch 处理程序将拒绝转换为实现。 await 将等待 catch 返回的 promise ,它从不拒绝。所以没有理由代码不会继续,因为 await 只会看到一个已实现(从未被拒绝)的 promise 。

请记住,catch 会返回一个新的 promise ,该 promise 将根据拒绝处理程序的操作进行结算。您的拒绝处理程序通过有效地返回 undefined 来抑制错误,从而实现 promise 。

这很像是你这样做的:

async function (){
let msg;
try {
msg = await bad();
} catch (e) {
console.log("This is an error: " + e);
}
console.log("I want to stop before executing this line ")
}

在您提出的评论中:

So there is no way other than including all my code inside the try block, and only use the one-liner .catch() if I have no more code to follow ?

只是为了解决这个问题:通常,最好的办法是除了代码的顶级入口点(例如,在代码的顶层调用的函数)之外的任何函数中根本不处理错误或通过事件处理程序)。过早处理错误是一种典型的反模式。允许它们传播到可以集中处理的调用方。

但是在适合在此级别处理错误的情况下,是的,try/catch 可能是您在 中使用以下逻辑的最佳选择尝试 block :

async function() {
try {
let msg = await bad();
console.log("I want to stop before executing this line ")
} catch (e) {
console.log("This is an error: " + e);
}
}

它还有一个优点,就是不在您不打算使用的包含作用域中声明一个变量。如果“one liner”对你来说很重要,那么 .catchcatch 之间没有太大区别:

async function() {
try {
let msg = await bad();
console.log("I want to stop before executing this line ")
} catch (e) { console.log("This is an error: " + e); }
}

或者您可以返回某种标志值:

async function() {
let msg = await bad().catch(e => { console.log("This is an error: " + e); return null; });
if (msg === null) {
return;
}
console.log("I want to stop before executing this line ")
}

但坦率地说,这确实是逆流而上。 :-)

关于javascript - 为什么在异步函数中捕获后仍然抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63508834/

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