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

azi*_*ium 14 javascript try-catch async-await 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)
  }
}()
Run Code Online (Sandbox Code Playgroud)

有关codepen的例子,如果有帮助的话

Ber*_*rgi 34

400/500不是错误,它是一个回应.当网络出现问题时,您只会遇到异常(拒绝).

服务器应答时,您必须检查它是否良好:

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)
}
Run Code Online (Sandbox Code Playgroud)