elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.79k stars 96 forks source link

How to catch a network error with cors (i.e: net::ERR_NAME_NOT_RESOLVED) #41

Closed belgattitude closed 5 years ago

belgattitude commented 5 years ago

Hi @elbywan, first of all thank for your nice work.

I could not find a way to catch network errors (net::ERR_NAME_NOT_RESOLVED -> failed to fetch) in cors mode. Using a middleware I can log them. Imagine the exampe below:

const logMiddleware = () => next => (url, opts) => {
    console.log(opts.method + "@" + url);
    return next(url, opts);
}

const wretchRequest = wretch()
    .options({ credentials: 'include', mode: 'cors' })
    .options({ headers: { Accept: 'application/json' } })
    .middlewares([
        logMiddleware()
    ]);

wretchRequest
           // AN INVALID URL (to provoke network failure)
            .url(`http://qsdkjlkjqslkdjlkqjsldkjqs.com/auth/token`)
            .options({ mode: 'cors' })
            .post({
                email: email,
                password: password,
            })
            .json(response => {
               // Here some code. 
            })
            .catch(error => {
               alert('THE NETWORK ERROR SHOULD BE REPORTED HERE ?');
               alert('UNFORTUNATELY, IT DOES NOT');
            });

The logMiddleware correctly shows the failure during the 'pre-flight/option request',

> OPTIONS http://qsdkjlkjqslkdjlkqjsldkjqs.com/auth/token net::ERR_NAME_NOT_RESOLVED
> Login error TypeError: Failed to fetch

But it's not reaching the catch block. Any Idea how to handle this in the catch ?

belgattitude commented 5 years ago

Oups sorry, I close this one. Because hot reload issue ;)