How would you handle errors gracefully inside a server action and display a meaningful message to the user?
Short answer
You wrap the risky part of your server action in a try and catch block, and instead of letting an unhandled error crash the request, you return a structured object describing what went wrong, which the calling client component can then read, often through the useActionState…
Advertisement
AModel answer
You wrap the risky part of your server action in a try and catch block, and instead of letting an unhandled error crash the request, you return a structured object describing what went wrong, which the calling client component can then read, often through the useActionState hook, to show an appropriate error message.
'use server';
export async function createAccount(prevState, formData) {
try {
await db.user.create({ data: { email: formData.get('email') } });
return { success: true };
} catch (error) {
return { success: false, message: 'This email is already registered.' };
}
}Real-world example
A signup form shows a clear message telling the user their email is already registered, instead of a generic broken error page, because the server action caught the database error and returned a friendly message.
Likely follow-ups
- Should sensitive error details ever be shown directly to the user?
- How do you log errors from server actions for debugging while still showing a friendly message?
Related topics