【问题标题】:try..catch not catching async/await errorstry..catch 没有捕捉到异步/等待错误
【发布时间】:2026-01-01 13:05:02
【问题描述】:

也许我误解了使用async/await 捕获错误应该如何从诸如https://jakearchibald.com/2014/es7-async-functions/ 和此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

【问题讨论】:

  • AFAK fetch api 不考虑 400/500 错误

标签: javascript async-await try-catch fetch-api


【解决方案1】:

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

【讨论】: