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.
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.