Sub topic 10
Expected errors as state, unexpected errors to error boundaries
This chapter assumes you can define a Server Function and use it with useActionState, as covered in earlier chapters. It also assumes you know what a React error boundary is. Here you will decide where each kind of failure goes.
Two kinds of failure
A Server Function can fail in two ways.
- Expected errors are outcomes you plan for: an empty title, a duplicate name, a record that no longer exists. The user can fix them, so the UI should show them next to the form.
- Unexpected errors are bugs or outages: the database is unreachable, a library throws, a null is dereferenced. The user cannot fix them, so the UI should show a fallback screen.
The rule is to return expected errors as data and let unexpected errors throw.
Expected errors as returned state
Returned values must be serializable, so return a plain object, not an Error instance. Keep the shape the same on every path so the client can read it without guessing.
// app/actions.js
'use server';
import { db } from './db';
export async function createNote(prevState, formData) {
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
return { ok: false, error: 'Title is required.' };
}
if (title.length > 100) {
return { ok: false, error: 'Title must be 100 characters or fewer.' };
}
const existing = await db.notes.findByTitle(title);
if (existing) {
return { ok: false, error: 'A note with this title already exists.' };
}
await db.notes.insert({ title });
return { ok: true, error: null };
}The client component stays small, because useActionState stores whatever the function returns.
// app/NoteForm.js
'use client';
import { useActionState } from 'react';
import { createNote } from './actions';
export function NoteForm() {
const [state, formAction, isPending] = useActionState(createNote, {
ok: false,
error: null,
});
return (
<form action={formAction}>
<input name="title" />
<button type="submit" disabled={isPending}>Add note</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}Unexpected errors as thrown errors
Do not wrap every call in try/catch and convert failures into { error: 'Something went wrong' }. That hides bugs and gives the user a form they cannot use. If db.notes.insert rejects, let it reject. React treats an error thrown from an action as a render error and passes it to the nearest error boundary.
Catch an error only when you can handle it. A unique-constraint violation is a good example, because you can turn it into a message. Rethrow anything else.
// app/actions.js (excerpt)
try {
await db.notes.insert({ title });
} catch (err) {
if (err.code === 'DUPLICATE') {
return { ok: false, error: 'A note with this title already exists.' };
}
throw err; // unexpected: let the error boundary handle it
}An error boundary is a class component that catches errors from the components below it.
// app/ErrorBoundary.js
'use client';
import { Component } from 'react';
export class ErrorBoundary extends Component {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
render() {
if (this.state.failed) {
return <p role="alert">Something went wrong. Please try again.</p>;
}
return this.props.children;
}
}Wrap the form, for example <ErrorBoundary><NoteForm /></ErrorBoundary>. Frameworks usually provide their own convention for this, such as a route-level error file. Check your framework's documentation.
Gotchas
- Event handlers. An error thrown from a Server Function called inside a plain
onClick, outside a transition, does not reach an error boundary. UsestartTransition(see theDeleteButtonexample) or catch it yourself. - Inconsistent state shape. If one branch returns
undefined,state.errorthrows on the client. Return the same shape from every path. - Authorization failures. Throwing for "not signed in" is reasonable, since a normal UI never triggers it. A user-triggerable case, such as editing a note someone else just deleted, is better returned as state.
Exercise
A Server Function calls db.notes.insert, and the database connection fails. Should the function catch the error and return { error: 'Failed to save' }, or let it throw? Give one reason.
Show answer
Let it throw. A connection failure is unexpected and the user cannot fix it, so it belongs in an error boundary. Swallowing it hides the bug from logs and error reporting, and leaves the user with a form that keeps failing. Return state only for problems the user can correct, such as validation errors.