编程语言
首页 > 编程语言> > javascript – try..catch没有捕获异步/等待错误

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

作者:互联网

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

解决方法:

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

标签:fetch-api,javascript,async-await,try-catch
来源: https://codeday.me/bug/20190919/1812449.html