try..catch 没有捕获异步/等待错误 [英] try..catch not catching async/await errors

查看:30
本文介绍了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.

Perhaps I misunderstood how catching errors with async/await is supposed to work from things articles like this https://jakearchibald.com/2014/es7-async-functions/ and this http://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html, but my catch block is not catching 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 不是错误,而是响应.只有在出现网络问题时,您才会收到异常(拒绝).

400/500 is not an error, it's a response. You'd only get an exception (rejection) when there's a network problem.

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

When the server answers, you have to check whether it's good or not:

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

这篇关于try..catch 没有捕获异步/等待错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆