1
const asyncThrowSampleApiFunction = async () => {
  throw new Error('SOMETHING');
};

const MyComponent = (SomeApiFunction) => {
  try {
    SomeApiFunction();
  } catch (err) {
    handleMyError(err);
  }

  return ...;
};

const c = MyComponent(() => {
  asyncThrowSampleApiFunction();    // call async function without 'await' or 'Promise.catch'
});

Is there any way to catch an unhandled promise rejection without Promise.catch or await?

In React.useEffect, we often use async function call without await statement. And I want to handle possible asynchronous errors in React.useEffect.

So I want to catch an unhandled promise rejection, but I can only find a global way to catch these rejection types.

(e.g. window.addEventListener('unhandledrejection', ...); )

I want to make my own ErrorBoundary. So I need to catch these rejections locally.

Is there any way to catch them?

Thanks.

2doo
  • 21
  • 4
  • 1
    Why can't you use `catch`? – code Dec 07 '21 at 04:19
  • you mean `Promise.catch`? – 2doo Dec 07 '21 at 04:25
  • Yes, `promise.catch()`. – code Dec 07 '21 at 04:26
  • You most certainly can use `async` functions in `useEffect`, you just can't provide one as the callback. See [this answer](https://stackoverflow.com/a/53572588/283366) – Phil Dec 07 '21 at 04:27
  • `React.useEffect` can receive only synchronous EffectCallback. So I should use it like Phil's referenced answer (`useEffect(() => { async f = ANY_FUNC_DEF; f(); });`). But this promise `f()` has no catch method. I want to make an error boundary which can catch async exceptions if client mistakenly do not add an promise rejection handler. – 2doo Dec 07 '21 at 04:33

1 Answers1

1

How can I catch an unhandled promise rejection locally without 'await' or 'Promise.catch'

You must catch a rejected promise somewhere with either .catch(), with the second argument to .then() or by bracketing an await with a try/catch. Those are your only three options.

So, technically if you're looking for something different than await or .catch(), you could use the second argument to .then() - though I suspect that's not really what you were asking for in which case, there are no other options.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • only two options.... OK. I'm going to find other way to implement it. Thanks for your answer! – 2doo Dec 07 '21 at 04:51
  • Well ackshually.... `asyncFunc().then(success => { ... }, error => { ... })`. No `try..catch` and technically no `.catch()` – Phil Dec 07 '21 at 04:58
  • @Phil - OK, that's really just a different way of doing `.catch()`, but I'll add that to my answer for completeness. – jfriend00 Dec 07 '21 at 05:16