catch不要再追异步

catch不要再追异步

本文介绍了在try..catch不要再追异步/待机错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我误解了如何与异步/的await 捕捉错误应该从事情的文章的工作是这样的这的,但我的块不捕400/500。

Perhaps I misunderstood how catching errors with async/await is supposed to work from things articles like this https://jakearchibald.com/2014/es7-async-functions/ and this http://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html, but my catch block is not catching 400/500.

async () => {
  let response
  try {
   let response = await fetch('not-a-real-url')
  }
  catch (err) {
    // not jumping in here.
    console.log(err)
  }
}()

推荐答案

400/500是不是一个错误,这是一个响应。你只会得到一个异常(拒绝)时,有一个网络问题。

400/500 is not an error, it's a response. You'd only get an exception (rejection) when there's a network problem.

在服务器答案,你必须检查它是否或不是:

When the server answers, you have to check whether it's good or not:

try {
    let response = await fetch('not-a-real-url')
    if (!response.ok) // or check for response.status
        throw new Error(response.statusText);
    let body = await response.text(); // or .json() or whatever
    // process body
} catch (err) {
    console.log(err)
}

这篇关于在try..catch不要再追异步/待机错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 14:01