首页 文章

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

提问于
浏览
4

我在使用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)
}

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

error messages

请参阅此处的代码示例:https://github.com/nyg/fetch-error-test

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

EDIT :fetch的catch块实际执行 .

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

1 回答

  • 3

    据我记忆,你不能在典型的 try->catchfetch 里面的 catch chain 中浏览器驱动的异常 .

    故意抛出CORS异常,让用户浏览站点,知道这些异常,如果你可以调用它们,并保护被叫api /服务器上可能的安全信息泄漏

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

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

相关问题