我试图在使用 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 控制台中:
See code example here: https://github.com/nyg/fetch-error-test 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;
}
据我所知,你不能catch
典型的浏览器驱动异常try->catch
or a catch chain
代替fetch
.
CORS 异常是有意抛出的,目的是让浏览网站的用户知道此类异常(如果您可以这样称呼它们),并防止被调用的 api/服务器上可能发生的安全信息泄露
Read here https://stackoverflow.com/questions/4844643/is-it-possible-to-trap-cors-errors之前关于是否可以使用异常处理程序捕获这些错误的讨论
如果请求抛出一个错误,该错误可能是响应的一部分,例如状态错误等,那么您可以捕获它并显示自定义消息
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)