Errors, loading, and recovery
Give each failure a useful boundary, preserve recoverable work and retry only when the operation permits it.
What you will be able to do
- Separate expected domain results from unexpected exceptions.
- Place route error and loading boundaries deliberately.
- Design retry rules around safety and failure category.
- Keep diagnostic details on the server with useful correlation.
Before this lesson
An invalid form is not a broken render
A missing required field is part of the normal domain conversation. A database connection failure is an unexpected infrastructure problem. A missing product is a route outcome. Treating all three as thrown generic errors loses the information needed for a useful response. Define which failures can be corrected by the user and which require a retry or operator investigation.
Expected failures should preserve the draft and identify the affected field or action. Unexpected failures should expose a stable recovery message while recording safe diagnostic context on the server. Do not send stack traces, SQL statements, credentials or private records to the browser simply because an error object contains them.
Place recovery around the work that can fail
An error boundary contains a failure in a subtree. In App Router, an error.tsx boundary is a Client Component because its fallback can offer an interaction such as reset. A boundary does not catch errors thrown by its own layout at the same level; a parent boundary or global-error arrangement is needed for higher failures. Place boundaries according to what remains useful when one region fails.
The example is a self-contained boundary file. Calling reset asks React and Next.js to attempt that subtree again; it cannot guarantee that a failing database has recovered. Keep the button actionable and explain the current condition. A dashboard with independent panels can preserve its navigation while one panel offers recovery.
Client module
"use client";
export default function ErrorPanel({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
return (
<section aria-labelledby="failure-title">
<h2 id="failure-title">This section could not load</h2>
<p>Your other work is still available. Try loading this section again.</p>
<button type="button" onClick={reset}>Try again</button>
</section>
);
}Model loading, empty and stale separately
Loading means the answer is not yet known. Empty means the request succeeded with no results. Stale means a previous result is visible while a refresh is in progress. Error means the attempt failed. A single boolean loading cannot describe all four states. A discriminated state model prevents impossible screens such as a success message and fatal error for the same request.
Suspense controls pending rendering, not every kind of failure. An event-handler exception or a rejected promise outside render needs deliberate handling in that interaction. If a refresh fails while useful old data is present, consider keeping the data with an explicit refresh error instead of replacing the whole screen with an empty placeholder.
Retry a safe operation, not a wish
Retries increase load and can duplicate effects. A read that failed transiently may be retried with a bounded exponential delay and jitter. A validation error should wait for corrected input. Authentication expiry should trigger the session flow. A write that timed out needs idempotency or reconciliation because it may already have committed.
Choose a budget: maximum attempts, overall deadline and which status categories qualify. Respect a valid server retry instruction when applicable and cap the delay. Avoid a loop that immediately retries every 500 response forever. The exercise below is a deterministic retry-policy kernel; adding randomized jitter belongs in a separately testable wrapper.
Make recovery explainable to a human
Attach a request or error correlation identifier to safe logs and the user-facing support message when needed. Record route, operation category, duration and outcome, while redacting secrets. A trace should help distinguish the browser, application server, database and upstream service. The error page alone cannot identify which dependency caused the delay.
Practice the failure deliberately: stop a mock upstream, return malformed data, make one server panel throw and reject a mutation after a delay. Then describe what remained usable and what the user can do next. A strong interview answer includes the recovery boundary, the persistence status of the user's work and the evidence needed to diagnose the incident.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGEA retry button guarantees recovery.
- A more accurate model
It retries the relevant work; a persistent dependency failure may still need a different remedy.
- How to check it
Inject a persistent server failure and observe the reset behavior.
- CLAIM TO CHALLENGEA refresh error must erase all previously loaded content.
- A more accurate model
Useful safe stale content can remain with an explicit refresh error, according to freshness requirements.
- How to check it
The lesson distinguishes loading, empty, stale and failed states.
Mistakes to catch in your own code
- Throwing validation errors into a full-page boundary.
- Assuming reset repairs a permanently failing dependency.
- Retrying a non-idempotent write after every timeout.
- Logging raw authentication headers or private request bodies.
Write it by hand
JavaScript logic playground
Choose a bounded retry decision
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Input is {method,status,attempt,idempotent}; attempt starts at 1.
- Retry status 429, 502, 503 or 504 only for GET or an explicitly idempotent operation, and only while attempt < 4.
- Return {retry,delayMs}; delay is min(8000,500*2^(attempt-1)), otherwise zero.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 4 test cases
- Retry a transient read
Input
{ "method": "GET", "status": 503, "attempt": 2, "idempotent": false }Expected
{ "retry": true, "delayMs": 1000 } - Do not repeat an unsafe write
Input
{ "method": "POST", "status": 504, "attempt": 1, "idempotent": false }Expected
{ "retry": false, "delayMs": 0 } - Stop at the attempt budget
Input
{ "method": "GET", "status": 503, "attempt": 4, "idempotent": false }Expected
{ "retry": false, "delayMs": 0 } - Do not retry validation
Input
{ "method": "POST", "status": 400, "attempt": 1, "idempotent": true }Expected
{ "retry": false, "delayMs": 0 }
Reveal the worked solution and reasoning
function solve(input) {
const transient = [429, 502, 503, 504].includes(input.status);
const safe = input.method === "GET" || input.idempotent === true;
const retry = transient && safe && input.attempt >= 1 && input.attempt < 4;
return { retry, delayMs: retry ? Math.min(8000, 500 * 2 ** (input.attempt - 1)) : 0 };
}Separate retry eligibility from the delay calculation so both can be inspected.
The contract deliberately omits jitter and Retry-After parsing; add those as explicit extensions rather than claiming they are present.
Idempotent means the operation has a real server guarantee, not just a client boolean in production.
Verify it in a real Next.js application
Next.js application lab
Separate retrying a failure from removing its cause
Open the local application route /errors after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Run the production lab and open /errors?fail=1. Inspect the Suspense-wrapped server panel and app/errors/error.tsx while the segment boundary is visible.
- Activate Retry this segment. The fail=1 input still causes the same deliberate exception, so rerunning the boundary should not be described as a repair.
- Use Remove the failing input. Its ordinary /errors link loads a clean document without the failing query or the current boundary state; confirm that the healthy heading and shared navigation are available.
- Visit /dashboard separately and compare a returned validation message with the thrown server-render failure. The task draft should survive its recoverable validation error.
- Implementation extension: add a transient read failure and a bounded client retry policy with cancellation. Define which errors are retryable and how a mutating request avoids duplicate effects before implementing retries.
Check the behavior
- The existing failed segment presents a readable error state while shared navigation remains available.
- Retry with the unchanged permanent fail=1 input remains a failure; removing that input restores the healthy page.
- Task validation is represented as form state and leaves the draft available, rather than being escalated to the route error boundary.
- The transient-failure extension stops at its retry budget, cancels obsolete work and does not blindly repeat unsafe writes.
Review the application reasoning
Development overlays and production boundaries differ. The lab includes a browser recovery scenario; extending it with transient errors requires additional checks. A successful recovery link does not prove that reset can repair an unchanged failing server input.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01How do expected errors differ from exceptions?
Expected errors are valid outcomes of the domain, such as a duplicate name or an invalid field. I represent them in a typed result so the interface can guide correction.
Unexpected exceptions indicate broken assumptions or unavailable dependencies. I log safe context and use a recovery boundary appropriate to the failed work.
Follow-up questions
- Where would a 404 product belong?
- How does a conflict differ from a server failure?
- Error handlingOfficial documentation
- Forms with Server ActionsOfficial documentation
02Does error.tsx catch every error in the route?
No. Its scope is the wrapped subtree, and errors in the layout at the same segment need a higher boundary. Event-handler and unrelated asynchronous errors also require their own handling.
I decide boundary placement from what should remain usable, then inject failures at each level to verify that the intended fallback actually appears.
Follow-up questions
- What happens if the fallback itself throws?
- When would you need global-error.tsx?
- Error handlingOfficial documentation
03Why can retrying a timed-out POST be dangerous?
The client knows it did not receive confirmation, not that the server did not commit. A second request can repeat the effect.
I use a stable idempotency key or retrieve the operation status before repeating a non-idempotent mutation. The interface should say confirmation is uncertain instead of inventing a failed state.
Follow-up questions
- What record would you persist for operation status?
- Which errors should never be automatically retried?
- Server Actions and mutationsOfficial documentation
- Error handlingOfficial documentation
04Should a background refresh failure remove existing data?
Not necessarily. If the previous data is still useful and safe, I keep it visible and show that refreshing failed. That preserves context and avoids turning a temporary network problem into an empty screen.
The policy depends on correctness needs. A financial balance or revoked permission may require stricter freshness than a public catalogue description.
Follow-up questions
- How do you announce the failure accessibly?
- What data cannot safely remain stale?
- Error handlingOfficial documentation
- SWR automatic revalidationOfficial documentation
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- Error handlingOfficial documentation
- Server Actions and mutationsOfficial documentation
- Forms with Server ActionsOfficial documentation
- SWR automatic revalidationOfficial documentation