Sub topic 6
Handling rejected promises
This chapter assumes you can write function components with props, use useState and useContext, and read basic promise code (then, catch, async/await). It also assumes you know what a Suspense boundary does. The earlier chapters showed that use reads a promise during render and suspends while the promise is pending. Here you will see what happens when the promise rejects, and the two ways to handle that.
What happens when a promise rejects
A promise has three states: pending, fulfilled, or rejected. use handles each one differently:
| Promise state | What `use(promise)` does | Who reacts |
|---|---|---|
| Pending | Suspends the component | The nearest `Suspense` boundary shows its fallback |
| Fulfilled | Returns the resolved value | The component renders normally |
| Rejected | Throws the rejection reason during render | The nearest error boundary shows its fallback |
A rejection is not returned as a value or as an error field. use throws it, the same way a bug in your render code would throw. React treats it as a render error, and only an error boundary can catch it.
If no error boundary sits above the component, the error propagates to the root. In React 19 an uncaught render error unmounts the whole tree. A rejected promise with no boundary therefore turns the page blank, not just the widget that asked for the data.
Option 1: an error boundary
An error boundary is a component that catches errors thrown while rendering its children and shows a fallback instead. React has no function-component API for this. You either write a class component or use a package.
The react-error-boundary package is the common choice:
import { Suspense, use } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
function Message({ messagePromise }) {
const content = use(messagePromise);
return <p>Here is the message: {content}</p>;
}
export function MessageContainer({ messagePromise }) {
return (
<ErrorBoundary fallback={<p>Could not load the message.</p>}>
<Suspense fallback={<p>Waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
</ErrorBoundary>
);
}While the promise is pending, Message suspends and the Suspense fallback shows. If the promise rejects, use throws, the ErrorBoundary catches the error, and "Could not load the message." replaces the whole subtree.
Boundary placement
In the example above, ErrorBoundary is outside Suspense. That is the usual order, but it is not required. A thrown error travels up to the nearest error boundary, and a suspended component travels up to the nearest Suspense boundary. The two searches are independent.
Placement still has a visible effect. When the error boundary is outside, an error replaces the whole region, including the loading state. When you put an error boundary inside a Suspense boundary, a rejection in one child can be contained while its siblings keep rendering. Place each boundary at the smallest region you are willing to replace with a fallback.
Writing your own boundary
If you cannot add a dependency, a class component works. This one logs the error and shows whatever fallback the parent passes in:
import { Component } from 'react';
export class MessageErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
console.error('Render error:', error, info.componentStack);
}
render() {
if (this.state.error) {
return this.props.fallback;
}
return this.props.children;
}
}getDerivedStateFromError runs during rendering and records that an error happened. componentDidCatch runs after the commit and is the place for side effects such as logging. You use the class the same way as ErrorBoundary above.
Option 2: a fallback value with `.catch`
Sometimes a failed request should not show an error screen. A missing optional message could render a default instead. In that case, handle the rejection on the promise itself, before it reaches use:
const messagePromise = new Promise((resolve, reject) => {
// ...
}).catch(() => 'No message found.');.catch returns a new promise. If the original rejects, the new promise fulfills with the value your handler returns. From the component's point of view the promise never rejects, so use returns 'No message found.' and no error boundary is involved.
Use .catch when the error has a sensible default and the user does not need to know it happened. Use an error boundary when the failure should interrupt the UI or offer a retry.
A small helper keeps the pattern consistent and makes sure the failure is still logged:
function withFallback(promise, fallbackValue) {
return promise.catch((error) => {
console.error('Request failed, using fallback:', error);
return fallbackValue;
});
}A .catch that silently swallows errors hides real outages. Log inside the handler, as above, or you will not find out when the endpoint breaks.
Choosing between the two
| Question | Error boundary | `.catch` fallback |
|---|---|---|
| Does the user need to know about the failure? | Yes | No |
| Is there a reasonable default value? | No | Yes |
| Where is the handling code? | Around the component | On the promise |
| Can you offer a retry button? | Yes | Not directly |
| Is the failure logged by default? | Only if you log it | Only if you log it |
Do not wrap `use` in try/catch
The try/catch statement is the first tool most developers reach for, and it is the wrong one here:
function Message({ messagePromise }) {
let content;
try {
content = use(messagePromise); // Not supported
} catch (error) {
content = 'No message found.';
}
return <p>{content}</p>;
}React does not support calling use inside a try/catch block. Suspending relies on throwing, so a catch clause around use can intercept the signal React uses to pause the component. Even if it appeared to work in one case, you would be depending on behavior the API does not promise.
Use one of the two supported options instead: an error boundary around the component, or .catch on the promise.
Note that try/catch is fine in other places. You can use it inside the async function that creates the promise. The restriction applies only to the use call itself.
Rejections that are not real failures
A promise from fetch fulfills even when the server answers with a 404 or 500 status. It rejects only on network-level failures such as a lost connection. If you pass that promise straight to use, an error page body can be treated as a valid response.
Convert HTTP errors into rejections yourself:
export function fetchMessage() {
return fetch('/api/message').then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.text();
});
}Throwing inside .then turns the returned promise into a rejected one. When a component later passes it to use, the error boundary sees an Error with a useful message.
Throw Error objects, not strings. A thrown string has no stack trace, and error-reporting tools handle it poorly. React will still catch any thrown value, but you lose debugging information.
Retrying after a failure
A rejected promise stays rejected. Calling use on the same promise again always throws the same reason. To retry, you need a new promise. This is one reason the previous chapter stressed keeping the promise stable. The new promise should be created by an event handler or an initializer, not by the render itself.
The next example holds the promise in state and replaces it when the user clicks "Try again". react-error-boundary calls onReset when its resetErrorBoundary function is called:
import { Suspense, use, useState } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
function fetchMessage() {
return fetch('/api/message').then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.text();
});
}
function Message({ messagePromise }) {
const content = use(messagePromise);
return <p>Here is the message: {content}</p>;
}
function ErrorFallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Could not load the message: {error.message}</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
export function MessageContainer() {
const [messagePromise, setMessagePromise] = useState(() => fetchMessage());
return (
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => setMessagePromise(fetchMessage())}
>
<Suspense fallback={<p>Waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
</ErrorBoundary>
);
}The sequence works like this:
- The initial
useStatecall creates one promise. Re-renders reuse it. - The promise rejects.
Messagethrows, andErrorFallbackrenders with the error. - The user clicks the button.
resetErrorBoundarytriggersonReset, which stores a new promise in state. The boundary then clears its error and renders its children again. Messagereceives the new pending promise and suspends. TheSuspensefallback shows until the request settles.
Resetting the boundary without replacing the promise would send you straight back to the error, because the old promise is still rejected. Both steps are needed.
Unhandled rejections and timing
A promise can reject before any component calls use on it. For example, a parent creates a promise, and the child that would read it is not rendered yet. The browser may report this as an unhandled promise rejection in the console, even though a boundary will catch the error later.
React attaches its own handlers when use reads the promise, so the error still reaches your boundary once the consuming component renders. The console message is noise in that case, but it can mislead you during debugging. If the message bothers you or your monitoring counts unhandled rejections, attach a no-op or logging .catch on a separate branch of the promise:
const messagePromise = fetchMessage();
messagePromise.catch((error) => console.error('Message request failed:', error));This .catch does not change messagePromise. It creates a second promise that handles the rejection for the console's benefit, while messagePromise itself still rejects when use reads it.
Promises passed from a Server Component
The server-to-client pattern from the Topic Spine adds one more place for rejections to occur. A Server Component can start a request without awaiting it and pass the promise to a Client Component:
import { Suspense } from 'react';
import { Message } from './Message';
async function fetchMessage() {
const response = await fetch('/api/message');
if (!response.ok) {
throw new Error('Request failed');
}
return response.text();
}
export default function App() {
const messagePromise = fetchMessage();
return (
<Suspense fallback={<p>Loading...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
);
}This is a sketch. Message must be a Client Component, and the fetch URL has to resolve on the server. If fetchMessage rejects, the rejection travels through the stream to the client, and use throws there. An error boundary around Message catches it like any other. Add one:
- The boundary must be a Client Component, because error boundaries rely on class lifecycle methods or hooks. Put
ErrorBoundaryin a file marked with'use client', or import it from a package that already is. - In production builds, React replaces the message of errors that originate on the server with a generic one, so that internal details do not reach the browser. Your
ErrorFallbackshould not depend onerror.messagefor server-originated failures. Show a general message and log the details on the server.
For a failure you can plan for, .catch on the server side is often simpler. Return a fallback value from the Server Component's promise, and the client never sees an error:
const messagePromise = fetchMessage().catch(() => 'No message found.');Common mistakes
- No error boundary at all. A rejection with nothing to catch it unmounts the entire tree. Put at least one boundary near the top of the app and more where partial failure is acceptable.
- Treating HTTP errors as success.
fetchdoes not reject on 404 or 500. Checkresponse.okand throw. - Resetting without a new promise. The boundary clears,
usereads the same rejected promise, and the error reappears immediately. - Creating the promise during render. A fresh promise on every render is a new pending promise every time. That causes repeated suspending and, for a failing request, an endless loop of rejections. Create the promise in a parent, in state, or on the server.
- Swallowing errors with
.catch. A fallback value is fine, but log the error first. - Relying on
error.messagefor server errors. Production builds hide it.
Exercises
Exercise
A component calls use(messagePromise) and the promise rejects. There is a Suspense boundary above the component but no error boundary. What happens, and why does the Suspense fallback not help?
Show answer
The error is thrown during render and no boundary catches it, so it propagates to the root and unmounts the whole tree. Suspense handles only pending promises. A rejection is a thrown error, and only an error boundary can catch it.
Exercise
You add a "Try again" button that resets an error boundary, but the error comes back immediately every time. The promise is created once with useState(() => fetchMessage()). What is wrong, and what is the fix?
Show answer
A rejected promise stays rejected, so resetting the boundary makes use read the same failed promise again. Create a new promise when resetting, for example onReset={() => setMessagePromise(fetchMessage())}, so the retry starts a new request.
Exercise
Your fetch to /api/message returns a 500 status, but the component renders the error page body as if it were the message. Why, and how do you make use throw instead?
Show answer
fetch fulfills its promise for any HTTP response and rejects only on network failures. Check response.ok in the function that builds the promise and throw an Error when it is false, so the promise rejects and use throws.
Exercise
Your teammate wraps use(messagePromise) in try/catch and returns a default string in the catch block. Name the problem and give two supported alternatives.
Show answer
React does not support use inside try/catch, because suspending relies on throwing and the catch clause can interfere with it. Alternatives: wrap the component in an error boundary, or attach .catch(() => 'default') to the promise before passing it to use.