try..catch没有捕获异步/等待错误

时间:2015-10-26 20:32:01

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

也许我误解了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

1 个答案:

答案 0 :(得分:29)

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