0 day streak
javascript / expert
Snippet

Type-Safe Error Handling in Server Actions

Server Actions often fail silently or return raw errors that are hard to handle in the UI. Returning a union type response ensures the client-side code can deterministically handle both success and failure states with full TypeScript support.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
'use server';
type ActionResponse = { success: true; data: string } | { success: false; error: string };
export async function updateUsername(formData: FormData): Promise<ActionResponse> {
const username = formData.get('username') as string;
try {
if (username.length < 3) throw new Error('Too short');
await db.user.update({ data: { username } });
return { success: true, data: 'Updated successfully' };
} catch (e) {
return { success: false, error: e instanceof Error ? e.message : 'Unknown error' };
}
}
nextjs
Breakdown
1
type ActionResponse = ...
Defines a strict contract for what the UI can expect from the backend.
2
catch (e) { return { success: false, ... } }
Gracefully captures exceptions and transforms them into a structured format.