Bird
Raised Fist0
NextJSframework~20 mins

Server-side error handling in NextJS - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Next.js Server Error Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Next.js server action error handler?

Consider this Next.js server action that throws an error. What will the client receive?

NextJS
export async function action() {
  try {
    throw new Error('Failed to save data')
  } catch (error) {
    return { success: false, message: error.message }
  }
}
A{"success": false, "message": "Failed to save data"}
BThe client receives a 500 Internal Server Error response with no JSON body
CThe client receives a JSON with { success: true }
DThe server crashes and restarts
Attempts:
2 left
💡 Hint

Look at what the catch block returns.

component_behavior
intermediate
2:00remaining
How does Next.js handle thrown errors in server components?

If a server component throws an error during rendering, what happens?

NextJS
export default function ServerComponent() {
  throw new Error('Render failed')
  return <div>Should not render</div>
}
AThe server silently ignores the error and renders an empty div
BThe component renders the error message inside the UI automatically
CNext.js shows a built-in error overlay in development and a 500 error page in production
DThe server restarts automatically without showing any error
Attempts:
2 left
💡 Hint

Think about Next.js default error handling behavior in dev and prod.

🔧 Debug
advanced
2:00remaining
Why does this Next.js API route fail to send a JSON error response?

Examine this API route code. Why does the client get a 500 error with no JSON?

NextJS
export default function handler(req, res) {
  try {
    throw new Error('Oops')
  } catch {
    res.status(500).json({ error: 'Server error' })
    return;
  }
  res.json({ success: true })
}
ABecause the function is missing async keyword
BBecause the catch block does not set the status code
CBecause the error is not re-thrown after catch
DBecause res.json is called twice, causing an error after the catch block
Attempts:
2 left
💡 Hint

Look at the flow after the catch block.

📝 Syntax
advanced
2:00remaining
Which option correctly throws a custom error in a Next.js server action?

Choose the code that correctly throws a custom error with a message and status code.

Athrow new Error('Not found') with status = 404
Bconst err = new Error('Not found'); err.status = 404; throw err
Cthrow new Error({ message: 'Not found', status: 404 })
Dthrow 'Not found' with status 404
Attempts:
2 left
💡 Hint

Remember how to add custom properties to Error objects.

state_output
expert
2:00remaining
What is the final state of errorMessage after this Next.js server action runs?

Given this server action, what is the value of errorMessage after execution?

NextJS
let errorMessage = ''

export async function action() {
  try {
    await Promise.reject(new Error('Failed to fetch'))
  } catch (error) {
    errorMessage = error.message
  }
  return errorMessage
}
A"Failed to fetch"
B"" (empty string)
Cundefined
DPromise rejected error
Attempts:
2 left
💡 Hint

Check how the catch block sets errorMessage.

Practice

(1/5)
1. What is the main purpose of using try...catch blocks in Next.js server-side functions?
easy
A. To style components dynamically
B. To catch and handle errors gracefully during server-side execution
C. To improve client-side rendering speed
D. To manage user authentication on the client

Solution

  1. Step 1: Understand server-side error handling

    Server-side functions can fail due to unexpected issues. Using try...catch helps catch these errors.
  2. Step 2: Purpose of try...catch

    The try block runs code that might fail, and the catch block handles errors to prevent crashes and provide feedback.
  3. Final Answer:

    To catch and handle errors gracefully during server-side execution -> Option B
  4. Quick Check:

    Error handling = catch errors gracefully [OK]
Hint: Try-catch blocks catch errors on the server side [OK]
Common Mistakes:
  • Confusing client-side and server-side error handling
  • Thinking try-catch improves UI styling
  • Assuming try-catch speeds up rendering
2. Which of the following is the correct syntax to catch errors in a Next.js server function?
easy
A. try { /* code */ } handle (error) { /* handle error */ }
B. catch { /* code */ } try (error) { /* handle error */ }
C. try { /* code */ } catch (error) { /* handle error */ }
D. try: { /* code */ } except (error) { /* handle error */ }

Solution

  1. Step 1: Recall JavaScript error handling syntax

    The correct syntax uses try { ... } catch (error) { ... } to catch errors.
  2. Step 2: Identify correct option

    try { /* code */ } catch (error) { /* handle error */ } matches the correct syntax. Other options use invalid keywords or order.
  3. Final Answer:

    try { /* code */ } catch (error) { /* handle error */ } -> Option C
  4. Quick Check:

    Correct try-catch syntax = try { /* code */ } catch (error) { /* handle error */ } [OK]
Hint: Remember: try then catch with parentheses [OK]
Common Mistakes:
  • Using incorrect keywords like except or handle
  • Swapping try and catch blocks
  • Omitting parentheses after catch
3. Consider this Next.js server function snippet:
export async function GET() {
  try {
    throw new Error('Failed to fetch data');
  } catch (error) {
    return new Response(error.message, { status: 500 });
  }
}

What will be the HTTP status code returned when this function runs?
medium
A. 400
B. 404
C. 200
D. 500

Solution

  1. Step 1: Analyze the thrown error

    The function throws an error with message 'Failed to fetch data'.
  2. Step 2: Check the catch block response

    The catch block returns a Response with status 500, indicating a server error.
  3. Final Answer:

    500 -> Option D
  4. Quick Check:

    Server error status code = 500 [OK]
Hint: Error caught returns status 500 by default [OK]
Common Mistakes:
  • Assuming status 200 despite error
  • Confusing 404 (not found) with server error
  • Ignoring the status property in Response
4. Identify the error in this Next.js server function code:
export async function GET() {
  try {
    const data = await fetch('https://api.example.com/data');
    return new Response(JSON.stringify(data));
  } catch (error) {
    return new Response('Error occurred', { status: 500 });
  }
}
medium
A. Not parsing fetch response to JSON before stringifying
B. Missing await on fetch call
C. Incorrect status code in catch block
D. No error handling implemented

Solution

  1. Step 1: Understand fetch response handling

    The fetch call returns a Response object, not the actual data. We must call response.json() to parse it.
  2. Step 2: Identify missing JSON parsing

    The code stringifies the Response object directly without parsing JSON, which is incorrect.
  3. Final Answer:

    Not parsing fetch response to JSON before stringifying -> Option A
  4. Quick Check:

    Parse response.json() before JSON.stringify() [OK]
Hint: Always parse fetch response with .json() before use [OK]
Common Mistakes:
  • Stringifying the Response object directly
  • Forgetting to await response.json()
  • Assuming fetch returns JSON data directly
5. You want to create a Next.js server function that fetches user data and returns a 404 status if the user is not found, or a 500 status if the fetch fails. Which code snippet correctly implements this error handling?
hard
A. export async function GET() { try { const res = await fetch('https://api.example.com/user'); if (!res.ok) { if (res.status === 404) return new Response('User not found', { status: 404 }); throw new Error('Fetch failed'); } const user = await res.json(); return new Response(JSON.stringify(user)); } catch { return new Response('Server error', { status: 500 }); } }
B. export async function GET() { const res = await fetch('https://api.example.com/user'); if (res.status === 404) return new Response('User not found', { status: 404 }); const user = await res.json(); return new Response(JSON.stringify(user)); }
C. export async function GET() { try { const user = await fetch('https://api.example.com/user').json(); return new Response(JSON.stringify(user)); } catch (error) { return new Response('User not found', { status: 404 }); } }
D. export async function GET() { try { const res = await fetch('https://api.example.com/user'); const user = await res.json(); return new Response(JSON.stringify(user)); } catch { return new Response('User not found', { status: 404 }); } }

Solution

  1. Step 1: Check for HTTP errors explicitly

    export async function GET() { try { const res = await fetch('https://api.example.com/user'); if (!res.ok) { if (res.status === 404) return new Response('User not found', { status: 404 }); throw new Error('Fetch failed'); } const user = await res.json(); return new Response(JSON.stringify(user)); } catch { return new Response('Server error', { status: 500 }); } } checks res.ok and handles 404 with a specific response, throwing errors for other failures.
  2. Step 2: Use try-catch for fetch failures

    The catch block returns a 500 status for server errors, correctly distinguishing error types.
  3. Final Answer:

    Correctly handles 404 if the user is not found and 500 if the fetch fails -> Option A
  4. Quick Check:

    Check res.ok and catch errors for 404 and 500 [OK]
Hint: Check res.ok and catch errors separately for 404 and 500 [OK]
Common Mistakes:
  • Not checking res.ok before parsing JSON
  • Returning 404 inside catch block incorrectly
  • Assuming fetch throws on 404 automatically