Performance: Error handling in server actions
This affects the responsiveness and stability of server actions, impacting how quickly errors are detected and handled without blocking the UI.
Jump into concepts and practice - no test required
export async function action(data) { try { const result = await fetch('/api/process', { method: 'POST', body: JSON.stringify(data) }); if (!result.ok) throw new Error('Failed request'); return await result.json(); } catch (error) { return { error: error.message }; } }
export async function action(data) { try { const result = await fetch('/api/process', { method: 'POST', body: JSON.stringify(data) }); if (!result.ok) throw new Error('Failed request'); return await result.json(); } catch (error) { throw error; // rethrow without handling } }
| Pattern | Server Blocking | UI Blocking | Error Feedback Speed | Verdict |
|---|---|---|---|---|
| Rethrow errors without handling | No blocking on server but unhandled promise rejection | Blocks UI update until error bubbles | Slow feedback, delayed error display | [X] Bad |
| Catch errors and return error object | No blocking | Immediate UI update with error | Fast feedback, smooth user experience | [OK] Good |
| Synchronous infinite loop on error | Blocks server event loop | Blocks all UI updates | No feedback, server freeze | [X] Bad |
| Log error and return controlled message | No blocking | Immediate UI update | Fast feedback, stable server | [OK] Good |
try...catch blocks inside Next.js server actions?try...catch allows catching these errors and responding properly instead of crashing the app.throw new Error('message') to create and throw errors.export async function addUser(data) {
try {
if (!data.name) throw new Error('Name is required');
// pretend to save user
return { success: true };
} catch (error) {
return { success: false, message: error.message };
}
}addUser({}) return?data.name is falsy, triggering the error throw.success: false and the error message.export async function updateUser(data) {
try {
if (!data.id) throw Error('User ID missing');
// update logic
} catch {
return { error: 'Update failed' };
}
}try...catch to throw new Error on invalid email and catch it to return a clear message.try...catch to validate email format and throw new Error if invalid, then catch and return error message correctly uses try...catch with throwing errors; others either skip server validation or misuse error handling.try...catch to validate email format and throw new Error if invalid, then catch and return error message [OK]