使用Fetch API时捕获“无法加载资源”

nyg*_*nyg 5 javascript error-handling cors fetch-api

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

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)
}
Run Code Online (Sandbox Code Playgroud)

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

错误讯息

在此处查看代码示例:https : //github.com/nyg/fetch-error-test

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

编辑:实际执行获取的catch块。

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)
}
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)

Sch*_*cat 3

据我记得,您不能catch在您的典型try->catch或.catch chainfetch

CORS 异常是有意抛出的,目的是让浏览网站的用户知道此类异常(如果您可以这样称呼它们),并防止被调用的 api/服务器上可能发生的安全信息泄露

阅读此处 之前关于是否可以使用异常处理程序捕获这些错误的讨论

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