Catching “Failed to load resource” when using the Fetch API

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-08 14:44:27

问题


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

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

See code example here: https://github.com/nyg/fetch-error-test

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

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

回答1:


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

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



来源:https://stackoverflow.com/questions/45512248/catching-failed-to-load-resource-when-using-the-fetch-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!