react
react copied to clipboard
[React 19] Export SuspenseException
Problem Statement
Currently, in React's use(promise) mechanism, there is no straightforward way to determine whether an exception originates from a promise suspended within the use hook. This makes it challenging for developers to:
- Accurately catch and handle errors related to suspended promises.
- Differentiate between errors caused by
use(promise)and other unrelated errors, complicating error handling logic.
Proposal
React should export either:
- A
SuspenseExceptionclass that can be used to identify errors originating from a promise suspension, or - A utility function to check whether a given error is caused by a suspended promise in
use(promise).
Example Usage
-
SuspenseException Class:
import { SuspenseException } from 'react'; try { use(fetchData()); } catch (error) { if (error === SuspenseException) { // Handle Suspense-related logic } else { // Handle other types of errors } } -
Utility Function:
import { isSuspenseException } from 'react'; try { use(fetchData()); } catch (error) { if (isSuspenseException(error)) { // Handle Suspense-related logic } else { // Handle other types of errors } }
Benefits
- Error differentiation: Clear distinction between promise suspensions and other errors.
- Enhanced debugging: Easier diagnosis of Suspense-related issues in both development and production.
- Safer error handling: Prevents unintended catches of non-Suspense errors during Suspense management.
Conclusion
By exporting either a SuspenseException or a utility function, React would offer developers more control over managing Suspense-related errors, improving both error handling and debugging in applications.
Agree. Currently, the handling of suspense looks very unreliable, here is an example from a real code: https://github.com/artalar/reatom/blob/e6b042f273dbacb221ed77923f6c8582e22236dc/packages/npm-react/src/index.ts#L209-L210
Have you considered the suggestions in the exception?
Suspense Exception: This is not a real error! It's an implementation detail of
useto interrupt the current render. You must either rethrow it immediately, or move theusecall outside of thetry/catchblock. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's.catchmethod and pass the result touse
Which use case are these suggestions not covering?
Hi, is this still open?
I am looking to fix some issues on this repo. I've previously worked on the react-native repo.
@eps1lon
Which use case are these suggestions not covering?
It is necessary for library authors to correctly decorate a render function. As I mentioned before, the current solution for library authors is not reliable and ugly: https://github.com/artalar/reatom/blob/e6b042f273dbacb221ed77923f6c8582e22236dc/packages/npm-react/src/index.ts#L209-L210