使用 Fetch API 时捕获 "Failed to load resource"
Catching "Failed to load resource" when using the 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)
}
我想捕获的错误只出现在 web 控制台中:
参见此处的代码示例:https://github.com/nyg/fetch-error-test
如何捕获这些错误以提供屏幕消息?
编辑:实际执行提取的 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;
}
据我所知,在典型的 try->catch
或 fetch
.
中的 catch chain
中,您不能 catch
浏览器驱动的异常
CORS 异常是有意抛出的,目的是让用户浏览站点,了解此类异常(如果您可以这样称呼它们),并保护被调用 api/server[= 上任何可能的安全信息泄漏15=]
阅读here
之前关于是否可以使用异常处理程序捕获这些错误的 SO 讨论
如果请求抛出的错误可能是响应的一部分,例如状态错误等,那么您可以捕获它并显示自定义消息
我在使用 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 控制台中:
参见此处的代码示例:https://github.com/nyg/fetch-error-test
如何捕获这些错误以提供屏幕消息?
编辑:实际执行提取的 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;
}
据我所知,在典型的 try->catch
或 fetch
.
catch chain
中,您不能 catch
浏览器驱动的异常
CORS 异常是有意抛出的,目的是让用户浏览站点,了解此类异常(如果您可以这样称呼它们),并保护被调用 api/server[= 上任何可能的安全信息泄漏15=]
阅读here 之前关于是否可以使用异常处理程序捕获这些错误的 SO 讨论
如果请求抛出的错误可能是响应的一部分,例如状态错误等,那么您可以捕获它并显示自定义消息