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

标签 javascript node.js error-handling async-await

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

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/

相关文章:

javascript - .__defineGetter__ 如何用于检测浏览器中的控制台是否打开

node.js - nodejs 中的 HTTP/0.9 支持

c++ - OpenGL 着色器编译错误 : unexpected $undefined at token "<undefined>"

swift - 为什么我得到 “' UIView'没有名为 'image'的成员,我该如何解决?

php - 将file_get_contents与错误的代理一起使用时,如何处理500个内部服务器错误?

javascript - 如何在php中将动态创建的表中的数据更新到数据库

javascript - 为什么我不能在函数开始时更改此按钮的文本?

javascript - 在 JavaScript 中找不到隐藏文本的 ID

node.js、vue.js 和 express.js 堆栈开发

javascript - session 不保存在函数调用内