some nooby questions
some nooby questions

Reputation: 693

Catching errors from one function inside another JavaScript React

I have two functions, login (in fileB.js):

export const login = async (data) => {
  try {
    const response = await auth.login(data);
    return response;
  } catch (e) {
    return new Error(e);
  }
};

and loginProcess (in fileA.js):

const loginProcess = (data) => {
    login(data)
      .then((response) => {
        if (response.status === 200) {

        }
      })
      .catch((e) => {
        setError(true);
      });
  };

If I have an error inside login() function it returns new Error(e) but inside loginProcess() the error from login() is not caught by catch but with then. I need to catch the new Error from login() inside catch in loginProcess(), how can I fix it?

Upvotes: 1

Views: 1814

Answers (1)

Yousaf
Yousaf

Reputation: 29282

You are converting promise rejection into promise fulfilment by returning an error object.

Retuning a non-promise value from the catch block will fulfil the promise returned by the login function with the return value of the catch block.

To reject the promise returned by the login function:

  • Re-throw the error caught by the catch block, or

  • Remove the try-catch block from the login function and let the calling code handle the error.

login function could be re-written as:

export const login = (data) => {
    return auth.login(data);
};

I suggest that you choose the second option and re-write the login function as shown above. There is no need for a catch block that just re-throws the error.

Upvotes: 4

Related Questions