简体   繁体   English

为什么try catch not catch等待function错误

[英]Why does try catch not catch await function errors

I know that if we have a try catch setup like this:我知道如果我们有这样的 try catch 设置:

try{
   runSyncFunction()
}
catch(err){
  cosole.log(err)
}

If there is an error in the runSyncFunction the catch error will fire.如果runSyncFunction中有错误,将触发 catch 错误。

As per my understanding if we have try catch setup like this:根据我的理解,如果我们尝试像这样捕获设置:

try{
   runAsyncFunction()
}
catch(err){
  cosole.log(err)
}

If there is an error in the runAsyncFunction the catch error will not fire because the function runs at a later time.如果runAsyncFunction中出现错误,则不会触发 catch 错误,因为 function 稍后会运行。

What I do not understand is why the catch error will not fire when we use await:我不明白为什么当我们使用 await 时不会触发 catch 错误:

try{
   await runAsyncFunction()
}
catch(err){
  cosole.log(err)
}

If there is an error in the async function this time, and since the javascript engine is waiting for it to finish running why would it not be able to catch the error in case of an error.如果这次异步 function 出现错误,并且由于 javascript 引擎正在等待它完成运行,为什么它在出现错误时无法捕获错误。

Edit1:编辑1:

router.post("/postDetails", async(req, res) => {
  try{
     let partID = await database.getPartID(partNumber[i])
     if (!partID) {
            throw createError(404, `"${partNumber[i]}" PartNumber not 
      found. Please re-enter the partnumber`)
    }
    //Other stuff  
  }
  catch(err){
    console.log(err) 
  }
})

Second function:第二个 function:

database.getPartID = async function getPartID(partNumber){
    try{
        let partID = await pool.query(`Select partID from parts where partNumber = '${partNumber}'`)
        return partID[0].partID
    }
    catch(err){
        console.log(err)
        return false
    }
}

I am returning false because the first async function does not throw an error message if there is an error in the second async function when there is a try catch block我返回 false 是因为第一个异步 function 不会在第二个异步 function 出现错误时抛出错误消息

These are some tips to use try...catch这些是使用try...catch的一些技巧

We can use try...catch for synchronous code.我们可以使用try...catch进行同步代码。

We can use try...catch (in combination with async functions) and the .catch() approaches to handle errors for asynchronous code.我们可以使用try...catch (结合async函数)和.catch()方法来处理异步代码的错误。

When returning a promise within a try block, make sure to await it if you want the try...catch block to catch the error.在 try 块中返回 promise 时,如果您希望try...catch块捕获错误,请确保await它。

Your second functions catch block is resolving the rejected promise.您的第二个函数 catch 块正在解析被拒绝的 promise。 Therefore your first function is not catching the error.因此,您的第一个 function 没有发现错误。 use return Promise.reject(err) in your second functions catch block, so that your first function can catch the error.在您的第二个函数 catch 块中使用return Promise.reject(err) ,以便您的第一个 function 可以捕获错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM