Bird
Raised Fist0
NextJSframework~10 mins

Error handling in server actions in NextJS - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to catch errors in a server action.

NextJS
export async function createUser(data) {
  try {
    // code to create user
  } catch (error) {
    [1];
  }
}
Drag options to blanks, or click blank then click option'
Aconsole.error(error)
Bthrow error
Creturn data
Dawait error
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'await error' causes syntax errors.
Returning data ignores the error.
Throwing error without handling may crash the app.
2fill in blank
medium

Complete the code to throw a custom error message in a server action.

NextJS
export async function deleteUser(id) {
  if (!id) {
    [1];
  }
  // deletion logic
}
Drag options to blanks, or click blank then click option'
Athrow new Error('User ID is required')
Bconsole.log('Missing ID')
Creturn 'No ID provided'
Dawait Error('ID missing')
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a string does not stop the function.
Logging the error does not throw it.
Using 'await' with Error is invalid.
3fill in blank
hard

Fix the error in the server action to properly handle rejected promises.

NextJS
export async function updateUser(data) {
  try {
    await updateDatabase(data).[1];
  } catch (error) {
    throw error;
  }
}
Drag options to blanks, or click blank then click option'
Athen()
Bcatch()
Cfinally()
Derror()
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'then()' does not catch errors.
Using 'finally()' runs regardless of errors.
There is no 'error()' method on promises.
4fill in blank
hard

Fill both blanks to return a JSON error response with status code 400.

NextJS
export async function serverAction(req) {
  try {
    // process request
  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), { status: [1], headers: { 'Content-Type': [2] } });
  }
}
Drag options to blanks, or click blank then click option'
A400
B'application/json'
C'text/plain'
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using status 500 means server error, not client error.
Setting content type to 'text/plain' will not parse as JSON.
5fill in blank
hard

Fill all three blanks to log the error, set a 500 status, and return a JSON error message.

NextJS
export async function handleRequest(req) {
  try {
    // handle request
  } catch (error) {
    [1];
    return new Response(JSON.stringify({ message: [2] }), { status: [3] });
  }
}
Drag options to blanks, or click blank then click option'
Aconsole.error(error)
B'Internal Server Error'
C500
Dthrow error
Attempts:
3 left
💡 Hint
Common Mistakes
Throwing error again may crash the server.
Returning a string instead of JSON object causes issues.

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

  1. Step 1: Understand server actions role

    Server actions run on the server and can fail due to errors like invalid input or database issues.
  2. Step 2: Purpose of try...catch

    Using try...catch allows catching these errors and responding properly instead of crashing the app.
  3. Final Answer:

    To catch errors and handle them gracefully during server-side operations -> Option C
  4. 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

  1. Step 1: Recall JavaScript error throwing syntax

    JavaScript uses throw new Error('message') to create and throw errors.
  2. Step 2: Check options for correct syntax

    Only throw new Error('Invalid input') matches the correct syntax; others use invalid keywords or formats.
  3. Final Answer:

    throw new Error('Invalid input') -> Option A
  4. 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

  1. Step 1: Analyze input and error condition

    The input object is empty, so data.name is falsy, triggering the error throw.
  2. Step 2: Understand catch block behavior

    The thrown error is caught, and the function returns an object with success: false and the error message.
  3. Final Answer:

    { success: false, message: 'Name is required' } -> Option A
  4. Quick Check:

    Error caught returns failure object = { success: false, message: 'Name is required' } [OK]
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

  1. Step 1: Check throw statement syntax

    The throw statement is valid without 'new', so no syntax error there.
  2. 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.
  3. Step 3: Evaluate best practice

    Without error parameter, you cannot log or use the error object, which is a common mistake in error handling.
  4. Final Answer:

    Catch block missing error parameter -> Option D
  5. 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

  1. Step 1: Understand server action validation

    Server actions should validate inputs and throw errors if invalid to prevent bad data.
  2. Step 2: Proper error handling pattern

    Use try...catch to throw new Error on invalid email and catch it to return a clear message.
  3. 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.
  4. Final Answer:

    Use try...catch to validate email format and throw new Error if invalid, then catch and return error message -> Option B
  5. 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]
Hint: Validate input inside try, throw error, catch and return message [OK]
Common Mistakes:
  • Skipping server-side validation
  • Throwing errors outside try block
  • Returning errors without throwing