"Failed to load resource" trap when using the Fetch API

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 are only shown in the web console:

error messages

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

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

EDIT : The catch fetch block is actually done.

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

Run codeHide result


+3


source to share


1 answer


As far as I remember, you cannot catch

browser throwable exceptions in typical try->catch

or catch chain

internally fetch

.

CORS exceptions are thrown with the intention of letting the user browse the site, be aware of such deviations, if you can name them, and to protect any possible leakage of protected information on the called api / server



Read here From a previous SO discussion on whether you can catch these errors with an exception handler

If the request raises an error that could be part of the response, like a status error, etc., you can catch it and show your own message

+2


source







All Articles