Miguel Stevens
Miguel Stevens

Reputation: 9230

Javascript not catching error using fetch

I have an authService which has the following fetch

export const handleForm = () => {

    return fetch('http://localhost:5000/login')
        .then(response => {
            if (!response.ok) {
                throw new Error("Email or password incorrect");
            } else {
                return response.json();
            }
        })
        .then(json => json)
        .catch(error => error);
};

I'm calling the method from my controller:

form.onsubmit = function (e) {
    handleForm(e)
        .then(response => {
            console.log(response);
            //setAuthenticatedUser(response);
            // setDomUser(response.user);
        })
        .catch(error => {
            console.log(error);
            document.querySelector('#error').innerHTML = error;
        })
};

I've tried a few things to get the error in my catch, in the controller But I keep getting the response callback fired. The error from my authService isn't being caught

I've Tried

Upvotes: 2

Views: 302

Answers (1)

str
str

Reputation: 45029

See Promise.prototype.catch():

Syntax Section

p.catch(onRejected);

[...]

The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.

Using .catch(error => error) as a callback returns the exception. So it neither "throws an error" nor "returns a Promise which is itself rejected". The promise returned by it is thus resolved, not rejected.

Simply remove .catch(error => error) and it will work. And when you're at it, also remove .then(json => json) as it is useless.

Upvotes: 3

Related Questions