【问题标题】:Catch UnhandledPromiseRejectionWarning during fetch在获取期间捕获 UnhandledPromiseRejectionWarning
【发布时间】:2018-12-06 04:03:46
【问题描述】:

我有一个代码:

function () {
  return new Promise((resolve, reject) => {
    try {
      fetch(URL, { method: METHOD, body: BODY })
        .then((res) => res.json())
        .then((json) => {
          resolve(json);
        })
        .catch((res) => {
          reject(res);
        })
    } catch (exception) {
      reject(exception);
    }
  });
}

当服务器响应不是 json 我得到了

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。

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

我读过

Cannot catch UnhandledPromiseRejectionWarning in promise,

Try Catch unable to catch UnhandledPromiseRejectionWarning,

“UnhandledPromiseRejectionWarning” error even when catch is present

但我的问题没有答案。

【问题讨论】:

    标签: javascript try-catch es6-promise


    【解决方案1】:

    当使用异步函数包装异步操作时,Try/catch 仅适用于异步操作。

    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

    【讨论】:

    • 链接到文档,或者对这种模式的其他解释?为什么会这样?
    • 我们可以在这里看到很多异步捕获的样本:dev.to/sobiodarlington/…
    • 完成!谢谢@danimal
    【解决方案2】:

    Try catch 将无法处理异步抛出的错误(即在 promise 中),您必须为此使用 .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块会返回一个新的rejected Promise。当函数被调用,如果没有catch()来处理请求,就会抛出你所说的错误。

    我已经解释了更多here

    【讨论】:

    • 不,没有帮助。我认为未处理的拒绝在这里res.json()
    • @SashaKos 请参阅Edit2
    • 感谢您的帮助,但问题仍然悬而未决。 res 总是有 json() 方法,因为它是 ES6 fetch API 的一部分。但是由于某些原因,json() 中的 json 解析错误没有被catch(() => ...) 捕获,可能是因为嵌套..
    • @SashaKos 你确定 json 解析错误没有被 .catch() 捕获吗?那会很奇怪。您可以 console.log 进入 catch 块并确认吗?
    • 我是多么愚蠢。我这里没有 CATCH someFunc().then((value)=>{}).CATCH((err)=>{console.log(err)})
    猜你喜欢
    • 2018-04-01
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 2017-05-05
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    相关资源
    最近更新 更多