Error handling in server actions helps you catch problems and respond properly, so your app stays reliable and users get clear feedback.
Error handling in server actions in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
export async function actionName(formData) { try { // your server logic here return { success: true }; } catch (error) { // handle error return { error: error.message }; } }
Use try...catch to catch errors inside server actions.
Return error info in a structured way so the client can show messages.
export async function saveUser(data) { try { await database.save(data); return { success: true }; } catch (error) { return { error: 'Failed to save user.' }; } }
export async function fetchData() { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) throw new Error('API error'); const data = await response.json(); return { data }; } catch (error) { return { error: error.message }; } }
This server action checks login data, throws errors for missing or wrong info, and returns success or error messages. It also sets a cookie on success.
import { cookies } from 'next/headers'; export async function loginAction(formData) { try { const username = formData.get('username'); const password = formData.get('password'); if (!username || !password) { throw new Error('Username and password are required'); } // Simulate user check if (username !== 'admin' || password !== '1234') { throw new Error('Invalid credentials'); } // Set a cookie on successful login cookies().set('token', 'fake-jwt-token'); return { success: true }; } catch (error) { return { error: error.message }; } }
Always return errors in a consistent format so the client can handle them easily.
Do not expose sensitive error details to users; keep messages friendly and safe.
Use try...catch blocks inside server actions to catch both synchronous and asynchronous errors.
Error handling keeps your app stable and user-friendly.
Use try...catch inside server actions to catch and return errors.
Return clear error messages so the client can show helpful feedback.
Practice
try...catch blocks inside Next.js server actions?Solution
Step 1: Understand server actions role
Server actions run on the server and can fail due to errors like invalid input or database issues.Step 2: Purpose of try...catch
Usingtry...catchallows catching these errors and responding properly instead of crashing the app.Final Answer:
To catch errors and handle them gracefully during server-side operations -> Option CQuick Check:
Error handling = To catch errors and handle them gracefully during server-side operations [OK]
- Confusing client-side state management with server error handling
- Thinking try...catch improves UI styling
- Assuming try...catch speeds up rendering
Solution
Step 1: Recall JavaScript error throwing syntax
JavaScript usesthrow new Error('message')to create and throw errors.Step 2: Check options for correct syntax
Only throw new Error('Invalid input') matches the correct syntax; others use invalid keywords or formats.Final Answer:
throw new Error('Invalid input') -> Option AQuick Check:
Throw error syntax = throw new Error('Invalid input') [OK]
- Using 'raise' instead of 'throw'
- Missing 'new' keyword before Error
- Incorrect punctuation in throw statement
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 };
}
}What will
addUser({}) return?Solution
Step 1: Analyze input and error condition
The input object is empty, sodata.nameis falsy, triggering the error throw.Step 2: Understand catch block behavior
The thrown error is caught, and the function returns an object withsuccess: falseand the error message.Final Answer:
{ success: false, message: 'Name is required' } -> Option AQuick Check:
Error caught returns failure object = { success: false, message: 'Name is required' } [OK]
- Assuming error is uncaught and crashes
- Expecting success true despite missing name
- Thinking function returns undefined
export async function updateUser(data) {
try {
if (!data.id) throw Error('User ID missing');
// update logic
} catch {
return { error: 'Update failed' };
}
}Solution
Step 1: Check throw statement syntax
The throw statement is valid without 'new', so no syntax error there.Step 2: Inspect catch block syntax
The catch block lacks an error parameter, which is allowed in modern JS but prevents accessing error details inside catch.Step 3: Evaluate best practice
Without error parameter, you cannot log or use the error object, which is a common mistake in error handling.Final Answer:
Catch block missing error parameter -> Option DQuick Check:
Catch needs error param to handle error details [OK]
- Assuming throw without new is invalid
- Ignoring missing return on success
- Thinking try should never throw
Solution
Step 1: Understand server action validation
Server actions should validate inputs and throw errors if invalid to prevent bad data.Step 2: Proper error handling pattern
Usetry...catchto thrownew Erroron invalid email and catch it to return a clear message.Step 3: Evaluate options
Usetry...catchto validate email format and thrownew Errorif invalid, then catch and return error message correctly uses try...catch with throwing errors; others either skip server validation or misuse error handling.Final Answer:
Use try...catch to validate email format and throw new Error if invalid, then catch and return error message -> Option BQuick Check:
Validate + throw + catch = Usetry...catchto validate email format and thrownew Errorif invalid, then catch and return error message [OK]
- Skipping server-side validation
- Throwing errors outside try block
- Returning errors without throwing
