1

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?

2
  • "it returns new Error(e)" - and that's wrong. One should not return errors, one should throw them as exceptions. Commented Sep 25, 2021 at 10:09
  • Also it's not logical to wrap the error in another Error - why do you even catch this error inside the function at all? Commented Sep 25, 2021 at 10:16

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I just changed return to throw and it works now, thanks!
I suggest writing return await auth.login(data) so the login function doesn't get removed from the stack trace and it doesn't set a refactoring trap in case someone adds back the try/catch at some point in the future (for instance to catch specific errors) or tries assigning the response to a variable instead of directly returning it, or appending something like || somethingElse. (See this issue.)
@CherryDT IMHO, login function doesn't needs to be async at all. login function can just return the promise and the calling code can do the necessary error handling.
That would obscure the fact that it's an asynchronous operation which most likely should be awaited by its caller because now the type wouldn't even be an AsyncFunction anymore. Yes technically it's correct what you say, I just think it can cause mistakes later on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.