捕获“未能加载资源".使用Fetch API时 [英] Catching "Failed to load resource" when using the Fetch API

查看:48
本文介绍了捕获“未能加载资源".使用Fetch API时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Fetch API时,我试图捕获与同一原始策略相关的许多错误,但未成功:

I'm trying to catch a bunch of errors related to the same origin policy when using the Fetch API but without any success:

window.onerror = (message, file, line, col, error) => console.log(error)
window.addEventListener('error', (error) => console.log(error))

try {
    fetch('https://www.bitstamp.net/api/ticker/').catch(e => {
        console.log('Caugth error:')
        console.log(e)
        console.log(JSON.stringify(e))
    })
}
catch (e) {
    console.log('try-catch')
    console.log(e)
}

我要捕获的错误仅出现在Web控制台中:

The errors I want to catch only appear in the web console:

在此处查看代码示例: https://github.com/nyg/fetch-错误测试

如何捕获这些错误以提供屏幕消息?

How can I catch these errors to provide an on-screen message?

编辑:提取的catch块实际上已执行.

EDIT: The fetch's catch block is actually executed.

fetch('https://www.bitstamp.net/api/ticker/')
    .then(response => response.text())
    .then(pre)
    .catch(e => {
        pre(`Caugth error: ${e.message}`)
    })

function pre(text) {
    var pre = document.createElement('pre')
    document.body.insertAdjacentElement('afterbegin', pre)
    pre.insertAdjacentText('beforeend', text)
}

pre {
    border: 1px solid black;
    margin: 20px;
    padding: 20px;
}

推荐答案

据我所知,您无法在典型的 try-> catch 中捕获浏览器驱动的异常code>或 fetch 内的 catch链.

As far as I remember, you can not catch browser driven exceptions in your typical try->catch or a catch chain inside of fetch.

故意抛出CORS异常,以使用户浏览站点,了解此类异常(如果可以将其称为),并防止在被调用的api/服务器上泄漏任何可能的安全信息

CORS exceptions are thrown with intent, to have the user browsing the site, know of such abnormalities if you may call them that, and to protect any leak of possible secure information on the called api/server

此处阅读在先前的SO讨论中,您是否可以使用异常处理程序捕获这些错误

Read here Of a previous SO discussion on whether you could catch these errors with an exception handler

如果请求抛出的错误可能是响应的一部分,例如状态错误等,那么您可能会捕获它并显示一条自定义消息

If the request throws an error that can be part of the response , like a status error and such, then you may catch it and show a custom message

这篇关于捕获“未能加载资源".使用Fetch API时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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