Sub topic 10
Expected Errors as State, Unexpected Errors to Error Boundaries
A Server Function can fail in two different ways. Some failures are normal outcomes that the user can fix, such as an empty title field. Others are faults that no form field can fix, such as a database outage. This chapter shows how to return the first kind as state and let the second kind throw to an error boundary.
It assumes you know React hooks and error boundaries at a basic level, async/await, and the useActionState hook from the previous chapters.
Two kinds of failure
The rule is simple. If the user can do something about the failure, return it as data. If only a developer or operator can fix it, throw it.
| Row | Expected errors | Unexpected errors |
|---|---|---|
| Examples | Empty field, title too long, duplicate name, wrong password | Database down, bug in your code, missing environment variable, no session on a route that requires one |
| Who can fix it | The user | A developer or operator |
| How the function reports it | Returns a plain object | Throws |
| Where it appears | Next to the form, through `useActionState` | In the nearest error boundary's fallback UI |
| Form input afterward | Kept so the user can edit it | Lost when the boundary replaces the form |
The diagram shows where each kind ends up.
Returning expected errors as state
Choose one result shape and use it in every Server Function that feeds a form. This example returns ok, a fieldErrors object and the submitted values. getSession and db are placeholders for your own modules, as in earlier chapters.
// app/actions.js
'use server';
import { getSession } from './auth';
import { db } from './db';
export async function createNote(prevState, formData) {
const session = await getSession();
if (!session) {
// Unexpected here: the page should already require sign-in.
throw new Error('Not signed in');
}
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
return { ok: false, fieldErrors: { title: 'Title is required.' }, values: { title } };
}
if (title.length > 100) {
return { ok: false, fieldErrors: { title: 'Use 100 characters or fewer.' }, values: { title } };
}
const existing = await db.notes.findByTitle(session.userId, title);
if (existing) {
return { ok: false, fieldErrors: { title: 'You already have a note with this title.' }, values: { title } };
}
await db.notes.insert({ title, ownerId: session.userId });
return { ok: true, fieldErrors: {}, values: { title: '' } };
}The function returns only plain objects with strings and booleans. These cross the network without trouble. Do not return an Error instance or a class instance. Serialization rules limit what can be sent, and the client has no use for a stack trace.
The Client Component reads the state and shows the messages.
// app/NoteForm.js
'use client';
import { useActionState } from 'react';
import { createNote } from './actions';
const initialState = { ok: false, fieldErrors: {}, values: { title: '' } };
export function NoteForm() {
const [state, formAction, isPending] = useActionState(createNote, initialState);
return (
<form action={formAction}>
<label htmlFor="title">Title</label>
<input
id="title"
name="title"
defaultValue={state.values.title}
aria-invalid={Boolean(state.fieldErrors.title)}
aria-describedby="title-error"
/>
{state.fieldErrors.title && (
<p id="title-error" role="alert">{state.fieldErrors.title}</p>
)}
<button type="submit" disabled={isPending}>Add note</button>
</form>
);
}Why the function returns the submitted values
React resets an uncontrolled form after its action finishes, even when the action returned an error. Without help, the user would lose what they typed. Returning values and using it as defaultValue puts the text back. Never return password fields this way.
On success the function returns an empty title, so the reset leaves the field blank and ready for the next note.
Letting unexpected errors throw
When a Server Function throws, the rejection travels back to the client. React rethrows it during render of the component that owns the action. The nearest error boundary catches it and renders its fallback. You do not need try/catch in the component.
React's built-in boundary is a class component. Many projects use the react-error-boundary package or a framework convention, such as an error.js file in Next.js. This plain version shows the mechanism.
// app/ErrorBoundary.js
'use client';
import { Component } from 'react';
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
render() {
if (this.state.error) {
return (
<div role="alert">
<p>Something went wrong. Please try again.</p>
<button onClick={() => this.setState({ error: null })}>Try again</button>
</div>
);
}
return this.props.children;
}
}Wrap the form where a failure should replace only that part of the page:
// app/page.js (a Server Component)
import { ErrorBoundary } from './ErrorBoundary';
import { NoteForm } from './NoteForm';
export default function Page() {
return (
<ErrorBoundary>
<NoteForm />
</ErrorBoundary>
);
}A boundary placed close to the form keeps the rest of the page alive. A boundary at the root replaces everything.
Error messages in production
Do not show error.message from a thrown server error to users and do not rely on it. In production builds, React and frameworks usually replace messages from the server with a generic one, so internals such as SQL text or file paths do not reach the browser. Some frameworks attach a digest you can match against server logs. The exact behavior differs by framework, so check yours. Always log the real error on the server.
Catching selectively
Sometimes a low-level error is really an expected one. A unique-constraint violation from the database is a common case. Convert that one error into a returned result and rethrow everything else.
// app/actions.js (excerpt)
'use server';
import { getSession } from './auth';
import { db } from './db';
export async function renameNote(prevState, formData) {
const session = await getSession();
if (!session) throw new Error('Not signed in');
const id = String(formData.get('id') ?? '');
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
return { ok: false, fieldErrors: { title: 'Title is required.' }, values: { title } };
}
try {
await db.notes.rename(id, session.userId, title);
} catch (error) {
if (error && error.code === 'DUPLICATE_TITLE') {
return { ok: false, fieldErrors: { title: 'That title is taken.' }, values: { title } };
}
console.error('renameNote failed', error);
throw error;
}
return { ok: true, fieldErrors: {}, values: { title } };
}The DUPLICATE_TITLE code is a placeholder. Your database driver defines its own error codes.
A catch-all catch that returns { error: 'Something went wrong' } for every failure looks safe. It has two costs. Bugs become invisible, because nothing reaches the boundary or your monitoring. The user also gets a message they cannot act on, next to a form they cannot fix.
Errors outside forms: event handlers and transitions
Not every Server Function call comes from a form. In an event handler, where you can see the error yourself, you have two choices.
If the failure is expected, return a result and branch on it:
// app/DeleteButton.js
'use client';
import { useState, useTransition } from 'react';
import { deleteNote } from './actions';
export function DeleteButton({ noteId }) {
const [isPending, startTransition] = useTransition();
const [message, setMessage] = useState(null);
return (
<>
<button
disabled={isPending}
onClick={() => {
setMessage(null);
startTransition(async () => {
const result = await deleteNote(noteId);
if (!result.ok) {
setMessage(result.message);
}
});
}}
>
{isPending ? 'Deleting…' : 'Delete'}
</button>
{message && <p role="alert">{message}</p>}
</>
);
}Here deleteNote returns { ok: false, message: 'This note was already deleted.' } for a missing note and { ok: true } otherwise. It still throws for a missing session.
If the function throws inside startTransition, React sends the error to the nearest error boundary, as it does for form actions. If you call the function in a plain async event handler without a transition, nothing connects the rejection to React. You get an unhandled promise rejection, and no boundary shows a fallback. Use a transition, or use try/catch and set state yourself.
Network failures also reject the call. A dropped connection or a server that is down surfaces as a thrown error on the client, so a boundary should be ready for it.
A decision checklist
- Can the user fix this by changing their input? Return it as state.
- Is it a failed permission or authentication check? Throw by default. A returned message can be appropriate when you want to show "Please sign in again", but never skip the check.
- Is it a bug, an outage, or an unknown error? Log it on the server and let it throw.
- Does your return value contain only strings, numbers, booleans, arrays and plain objects? If not, simplify it.
- Does the form keep the user's input after a returned error? If not, return
valuesand usedefaultValue.
Exercise
A Server Function used with useActionState catches every error from the database and returns { error: 'Something went wrong.' }. Name two problems with this design and describe a better one.
Show answer
First, real bugs and outages never reach an error boundary or your monitoring, so they are easy to miss. Second, the user sees a message they cannot act on, next to a form that stays usable but still fails. A better design catches only the specific errors that are expected, such as a duplicate-key code, and returns them as field errors. It logs and rethrows everything else so the nearest error boundary handles it.
Exercise
A user submits a form, the action returns { ok: false, fieldErrors: { title: 'Title is required.' } }, and the message appears, but the user's other fields are now empty. Why does this happen, and how do you fix it?
Show answer
React resets an uncontrolled form after its action finishes, even when the action returned an error. To fix it, return the submitted values in the result, for example values: { title, body }, and set each input's defaultValue from state.values. Do not return sensitive fields such as passwords.