Error Handling in Server Actions
You'll learn how to handle errors thrown by Server Actions using try/catch blocks or error boundaries.
When a Server Action encounters a problem — like a database connection failure, validation error, or authorization issue — you need a way to communicate that failure back to the client. Since Server Actions run on the server but are called from components (Server or Client), React provides two complementary approaches to handle these errors.
The Two Approaches
Throwing errors in a Server Action will trigger React's error boundary mechanism on the client side. The error propagates up the component tree until it hits an error boundary, just like any other React error. This is great for unexpected failures you want to handle at a higher level.
Try/catch blocks give you fine-grained control. Wrap your Server Action call in a try/catch to handle errors locally, show specific error messages to the user, or recover gracefully without unmounting the entire component tree.
Mental Model: Remote Function Calls
Think of Server Actions like calling a remote API endpoint. The function executes somewhere else (the server), and you need to handle both success and failure cases. The difference is React makes this feel seamless — thrown errors naturally integrate with React's error boundary system, while caught errors let you handle failures inline.
// In a Server Action
'use server'
export async function updateProfile(formData) {
const name = formData.get('name');
if (!name) throw new Error('Name is required');
// ... database update
}
// In a component with try/catch
async function handleSubmit(formData) {
try {
await updateProfile(formData);
setMessage('Success!');
} catch (error) {
setError(error.message);
}
}
Key Takeaway: Server Actions can throw errors to trigger error boundaries or be wrapped in try/catch for local error handling — choose based on whether you want component-level or boundary-level recovery.