0
0
NextJSframework~10 mins

Error handling in server actions in NextJS - Interactive Code Practice

Choose your learning style9 modes available
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.