javascript / expert
Snippet
Typsichere Fehlerbehandlung in Server Actions
Server Actions schlagen oft lautlos fehl oder geben Rohfehler zurück, die im UI schwer zu handhaben sind. Die Rückgabe eines Union-Type-Response stellt sicher, dass der clientseitige Code sowohl Erfolgs- als auch Fehlerzustände mit voller TypeScript-Unterstützung deterministisch handhaben kann.
snippet.js
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
Erklärung
1
type ActionResponse = ...
Definiert einen strikten Vertrag darüber, was das UI vom Backend erwarten kann.
2
catch (e) { return { success: false, ... } }
Fängt Ausnahmen elegant ab und transformiert sie in ein strukturiertes Format.