简体   繁体   English

尽管有catch块,但仍会抛出异常

[英]Fetch still throws despite having catch block

fetch('https://api.postcodes.io/postcodes/aassdd')
  .then((resp) => {
    console.log(resp.status);
  })
  .catch((e) => { console.log('ha'); });

For some odd reason the code above will still throw error and execute the .then statement afterwards. 出于某种奇怪的原因,上面的代码仍然会引发错误并在之后执行.then语句。 Is there a way to fix this ? 有没有办法解决这个问题 ?

Edit: fiddle 编辑: 小提琴

Most browser developer consoles normally logs 404 errors by default, and some may, or can be configured to, log all requests. 大多数浏览器开发人员控制台通常默认情况下都会记录404错误,并且某些(或可以将其配置为)记录所有请求。

控制台截图

The fact that you see see an error here doesn't mean a catch-able JavaScript exception was thrown, in addition to JavaScript console logs and throw exceptions, the browser console also shows other things. 您在此处看到错误的事实并不意味着抛出了可捕获的JavaScript异常,除了JavaScript控制台日志和throw异常之外,浏览器控制台还显示了其他内容。

There isn't anything you can do in your code to stop this error from appearing in the console, but some consoles would let you hide those requests from the console. 您无法在代码中采取任何措施来阻止此错误出现在控制台中,但是某些控制台会让您从控制台中隐藏那些请求。

Also, fetch does not throw an error on typical error response codes like 404. This is to make it more-flexible, and let you decide if you still want the content, even if it is a 404 response code. 同样, fetch不会在诸如404这样的典型错误响应代码上抛出错误。这是为了使其更加灵活,并让您确定是否仍要该内容,即使它是404响应代码也是如此。

If you want to throw an error on a non-200 status code, you could do this: 如果要在非200状态代码上引发错误,则可以执行以下操作:

fetch('https://api.postcodes.io/postcodes/aassdd')
  .then((resp) => {
    if (resp.status !== 200) {
        throw new Error('Invalid status code: ' + resp.status);
    }
  })
  .catch((e) => { console.log('ha'); });

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

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