Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Error handling in server actions
📖 Scenario: You are building a Next.js app that lets users submit feedback through a form. The form sends data to a server action that saves the feedback. You want to handle errors gracefully if saving fails.
🎯 Goal: Create a server action that saves feedback data and handles errors by returning a clear message. Then connect it to a simple form component that calls this action.
📋 What You'll Learn
Create a server action function called saveFeedback that accepts a FormData object
Add a configuration variable simulateError to control if the save should fail
Use try...catch inside saveFeedback to handle errors and return an error message
Create a React functional component FeedbackForm that uses the saveFeedback server action on form submission
💡 Why This Matters
🌍 Real World
Handling errors in server actions is important for building reliable web apps that communicate with servers safely and inform users about issues.
💼 Career
Understanding server actions and error handling is essential for Next.js developers working on full-stack React applications.
Progress0 / 4 steps
1
Create the server action function
Create an async server action function called saveFeedback that accepts a parameter formData. Inside, extract the feedback text from formData using formData.get('feedback') and store it in a variable called feedbackText.
NextJS
Hint
Use export async function saveFeedback(formData) to define the server action. Use formData.get('feedback') to get the feedback text.
2
Add error simulation configuration
Inside the saveFeedback function, create a constant called simulateError and set it to false. This will control if the save operation should simulate an error.
NextJS
Hint
Declare const simulateError = false; inside the function to control error simulation.
3
Add error handling logic
Wrap the save logic inside a try...catch block. Inside try, if simulateError is true, throw a new Error with message 'Simulated save error'. Otherwise, simulate saving by returning { success: true, message: 'Feedback saved' }. In catch, return { success: false, message: error.message }.
NextJS
Hint
Use try...catch to handle errors. Throw an error if simulateError is true. Return success or error objects accordingly.
4
Create the feedback form component
Create a React functional component called FeedbackForm. Inside, create a form with a textarea named feedback and a submit button. Use the saveFeedback server action as the form's action. Add an aria-label to the textarea with value 'Feedback input' for accessibility.
NextJS
Hint
Create a form with action={saveFeedback}. Add a textarea with name="feedback" and aria-label="Feedback input". Add a submit button.
Practice
(1/5)
1. What is the main purpose of using try...catch blocks inside Next.js server actions?
easy
A. To manage state in React components
B. To improve client-side rendering speed
C. To catch errors and handle them gracefully during server-side operations
D. To style components dynamically
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
Using try...catch allows 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 C
Quick Check:
Error handling = To catch errors and handle them gracefully during server-side operations [OK]
Hint: Try...catch in server actions catches server errors [OK]
Common Mistakes:
Confusing client-side state management with server error handling
Thinking try...catch improves UI styling
Assuming try...catch speeds up rendering
2. Which of the following is the correct syntax to throw an error inside a Next.js server action?
easy
A. throw new Error('Invalid input')
B. raise Error('Invalid input')
C. error('Invalid input')
D. throw Error: 'Invalid input'
Solution
Step 1: Recall JavaScript error throwing syntax
JavaScript uses throw 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 A
Quick Check:
Throw error syntax = throw new Error('Invalid input') [OK]
Hint: Use 'throw new Error(message)' to throw errors [OK]
Common Mistakes:
Using 'raise' instead of 'throw'
Missing 'new' keyword before Error
Incorrect punctuation in throw statement
3. Consider this Next.js server action code:
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?
medium
A. { success: false, message: 'Name is required' }
B. { success: true }
C. Throws an uncaught error
D. Returns undefined
Solution
Step 1: Analyze input and error condition
The input object is empty, so data.name is falsy, triggering the error throw.
Step 2: Understand catch block behavior
The thrown error is caught, and the function returns an object with success: false and the error message.
Final Answer:
{ success: false, message: 'Name is required' } -> Option A
Hint: Empty name triggers error, caught returns failure object [OK]
Common Mistakes:
Assuming error is uncaught and crashes
Expecting success true despite missing name
Thinking function returns undefined
4. Identify the error in this Next.js server action code:
export async function updateUser(data) {
try {
if (!data.id) throw Error('User ID missing');
// update logic
} catch {
return { error: 'Update failed' };
}
}
medium
A. Try block should not throw errors
B. Missing parentheses in throw statement
C. Function must return a value on success
D. Catch block missing error parameter
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 D
Quick Check:
Catch needs error param to handle error details [OK]
Hint: Always include error parameter in catch for details [OK]
Common Mistakes:
Assuming throw without new is invalid
Ignoring missing return on success
Thinking try should never throw
5. You want to create a Next.js server action that validates user input and throws an error if the email is invalid. Which approach correctly combines validation and error handling?
hard
A. Throw error outside try block and catch inside to handle validation
B. Use try...catch to validate email format and throw new Error if invalid, then catch and return error message
C. Validate email on client only; server action should not throw errors
D. Return error messages without throwing errors in server actions
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
Use try...catch to throw new Error on invalid email and catch it to return a clear message.
Step 3: Evaluate options
Use 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.
Final Answer:
Use try...catch to validate email format and throw new Error if invalid, then catch and return error message -> Option B
Quick Check:
Validate + throw + catch = Use try...catch to validate email format and throw new Error if invalid, then catch and return error message [OK]