在提取期间捕获UnhandledPromiseRejectionWarning

时间:2018-06-27 09:54:46

标签: javascript try-catch es6-promise

我有一个代码:

return

当服务器不响应json时

  

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。该错误是由于在没有catch块的情况下抛出异步函数而引起的,或者是由于拒绝了未经.catch()处理的诺言而引起的。

我知道try-catch不会捕获异步抛出。

我已阅读

Cannot catch UnhandledPromiseRejectionWarning in promise

Try Catch unable to catch UnhandledPromiseRejectionWarning

“UnhandledPromiseRejectionWarning” error even when catch is present

但是我的问题没有答案。

2 个答案:

答案 0 :(得分:3)

Try catch将无法处理异步引发的错误(即,按承诺),为此必须使用.catch()

JSfiddle

function someFunc() {
    return new Promise((resolve, reject) => {

        fetch(URL, {method: METHOD, body: BODY})
            .then((res) => res.json())
            .then((json) => {
                resolve(json);
            })
            .catch((err) => {
                reject(err);
            })
    });
}

someFunc()
.then((value)=>{})
.catch((err)=>{console.log(err)})

编辑:  当服务器没有回应json但有错误时,您返回的承诺为rejected。因此,您应确保在函数调用(即.catch())上调用someFunc().catch(()=>{})。如果未处理您拒绝的承诺(没有捕获),则会出现此错误。

Edit2:糟糕。抱歉,您的问题有误,但我想解释还是一样。 如果res上没有json()方法,则在调用res.json()时会抛出以下错误:

Uncaught TypeError: res.json() is not a function

error将被您的.catch()阻止捕获。 现在catch块将返回新的被拒绝的诺言。。调用该函数并且如果没有catch()处理请求时,将抛出您正在谈论的错误。 >

我已经解释了更多here

答案 1 :(得分:0)

尝试/捕获仅在使用异步函数将其包装时才适用于异步操作。

fetchSomething = async url => {
  try {
     await fetch(url)
  } catch (error) {
     // We will see error here
  }
}

在此处查看其他捕获异步错误的方法:https://dev.to/sobiodarlington/better-error-handling-with-async-await-2e5m

相关问题