question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unhandled promise rejection error

See original GitHub issue

I’m not sure how errors are supposed to be handled. I have the following function that returns a promise:

  getFacebookToken(): Promise<string> {
    return LoginManager.logInWithPermissions(['public_profile'])
      .then((response) => {
        if (response.isCancelled) {
          // This error is not handled.
          throw Error('Request canceled');
        } else {
          return AccessToken.getCurrentAccessToken();
        }
      })
      .then((response) => response.accessToken)
  }

When I use the above with useAsyncTask and if the promise throws an error, then this is not handled and, also, the task.error is always null.

Thank you in advance.

PS. I’m using this in React Native, not ReactJS.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
gsavvidcommented, Nov 11, 2020

Thank you very much, that’s a great solution.

Here’s the Typescript equivalent of your solution in case someone else stumbles upon this:

const useAsyncTaskIgnoringError = <Result, Args extends unknown[]>(func: (c: AbortController, ...args: Args) => Promise<Result>): AsyncTask<Result, Args> => {
  const task = useAsyncTask(func);
  return useMemo(() => ({
      ...task,
      start: async (...args: Args) => {
        try {
          return await task.start(...args);
        } catch (e) {
          // We ignore this error because it's handled with the state.
          console.log('Error: ' + e);
        }
      },
    }), [task]);
};
1reaction
dai-shicommented, Nov 11, 2020

Thanks for the clarification.

I could add a catch at the end of my promise if that’s what you mean but then the question is how will the component get notified that the promise was rejected? Perhaps I’m missing something obvious here.

Your understanding is correct. So, we shouldn’t add catch there.

What I mean is something like this:

export default function SignInPage(props: SignInPageProps) {
  const {start, result: facebookLogin, started: facebookLoginLoading, error: facebookError} = useAsyncTask(fetchLoginWithFacebook);
  const startLoginWithFacebookTask = useCallback(async () => {
    try {
      await start();
    } catch (e) {
      // ignore
    }
  }, [start]);

  return (
    <LoadingSignInView
      isLoading={facebookLoginLoading}
      title={Strings.signInTitle}
      subtitle={Strings.signInSubtitle}
      bottomButtonPrompt={Strings.signUpPrompt}
      bottomButtonText={Strings.signUp}
      onFacebookButtonPress={startLoginWithFacebookTask}
    />
  );
}

It looks annoying to do this every time. As the philosophy of react-hooks-async is composability, we create a new hook instead of modifying useAsyncTask.

const useAsyncTaskIgnoringError = (func) => {
  const task = useAsyncTask(func);
  return useMemo(() => ({
    ...task,
    start: async (...args) => {
      try {
        await task.start(...args);
      } catch (e) {
        // we ignore this error because it's handled with state
      }
    },
  }), [task]);
};

Hope it helps.

Read more comments on GitHub >

github_iconTop Results From Across the Web

What is an unhandled promise rejection? - javascript
A rejected promise is like an exception that bubbles up towards the application entry point and causes the root error handler to produce...
Read more >
Tracking Unhandled Promise Rejections
When a promise is rejected, it looks for a rejection handler. If it finds one, like in the example above, it calls the...
Read more >
Handling those unhandled promise rejections with JS async ...
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was ......
Read more >
What is UnhandledPromiseRejectionWarning
The Promise.reject() method returns a Promise object that is rejected with a given reason. The unhandledrejection event is sent to the global scope...
Read more >
Unhandled Promise Rejection Warning
The unhandledRejection event is emitted whenever a promise rejection is not handled. “Rejection” is the canonical term for a promise reporting ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found