Expected errors are those that can occur during the normal operation of the application, such as those from server-side form validation or failed requests. These errors should be handled explicitly and returned to the client.
Server Functions
You can use the useActionState hook to handle expected errors in Server Functions.
For these errors, avoid using try/catch blocks and throw errors. Instead, model expected errors as return values.
app/actions.ts
'use server'
export async function createPost(prevState: any, formData: FormData) {
const title = formData.get('title')
const content = formData.get('content')
const res = await fetch('https://api.vercel.app/posts', {
method: 'POST',
body: { title, content },
})
const json = await res.json()
if (!res.ok) {
return { message: 'Failed to create post' }
}
}
You can pass your action to the useActionState hook and use the returned state to display an error message.
app/ui/form.tsx
'use client'
import { useActionState } from 'react'
import { createPost } from '@/app/actions'
const initialState = {
message: '',
}
export function Form() {
const [state, formAction, pending] = useActionState(createPost, initialState)
return (
<form action={formAction}>
<label htmlFor="title">Title</label>
<input type="text" id="title" name="title" required />
<label htmlFor="content">Content</label>
<textarea id="content" name="content" required />
{state?.message && <p aria-live="polite">{state.message}</p>}
<button disabled={pending}>Create Post</button>
</form>
)
}
Top comments (3)
this is such a great reminder. people default to try/catch for everything because that's how we wrote API routes, but returning a state is so much cleaner for form validation. quick q though: do you still wrap the fetch call in a try/catch just in case the network completely dies, or let it bubble to the error.tsx boundary?
I only catch what the user can act on. Expected failures (validation, 4xx) get returned as state. For the network call itself I’ll wrap just the fetch and return a “couldn’t reach the server, try again” state, mainly because error.tsx would wipe the form input. Anything truly unexpected (5xx, bugs) I let bubble to error.tsx. One gotcha: keep redirect() outside the try/catch, since it works by throwing.
That distinction makes a lot of sense, especially preserving the form state instead of sending users through an error boundary for a recoverable network failure. Keeping expected validation and 4xx responses as actionable state also makes the UI much easier to reason about. And the redirect() detail is a great catch — treating it like an ordinary exception inside a broad try/catch can turn a successful navigation into a confusing failure. Nice, practical separation between errors users can recover from and errors the application should surface.