try..catch 没有捕捉到 async/await 错误

try..catch not catching async/await errors

也许我误解了 async/await 捕获错误应该如何从这样的文章中工作 https://jakearchibald.com/2014/es7-async-functions/ and this http://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html,但我的 catch 块没有捕获 400/500。

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

example on codepen if it helps

400/500 不是错误,而是响应。只有在出现网络问题时才会出现异常(拒绝)。

当服务器应答时,你必须检查它是否good

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)
}