2

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

  • throw new Error();
  • Promise.reject();
Miguel Stevens
  • 8,631
  • 18
  • 66
  • 125

1 Answers1

3

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.

str
  • 42,689
  • 17
  • 109
  • 127