繁体   English   中英

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

[英]try..catch not catching async/await errors

也许我误解了使用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)
  }
}()

codepen 上的示例(如果有帮助)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM