Skip to content

Expected Failures Have a Result Shape

The Course
•
18 min study

The decision

Validation errors, a duplicate title and an unavailable database are different outcomes. Expected errors should be useful to the form; unexpected failures should reach logging and an error boundary rather than exposing server details.

Read, predict, run

The function returns a discriminated result: ok selects data or a stable error code. The form displays its result without pretending a returned error field is a thrown exception. Keep the result serializable across the action boundary:

JavaScript
export function run({ title, exists }) {
  if (!title.trim()) return { ok: false, code: "invalid_title" };
  if (exists) return { ok: false, code: "duplicate_title" };
  return { ok: true, title: title.trim() };
}

Before pressing Run, predict what run returns for {"title": "", "exists": false} and {"title": "Forms", "exists": true}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Expected Failures Have a Result Shape Next.js · 8 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import ProbeForm from "./ProbeForm.jsx"; import { examples } from "@/lib/contract.js"; import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Expected Failures Have a Result Shape</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <ProbeForm initial={examples[0][0]} /> <Cases /> </main> ); } "use server"; import { run } from "@/lib/contract.js"; export async function evaluate(previous, formData) { const raw = formData.get("input"); if (typeof raw !== "string") return { error: "Enter JSON.", result: null }; let input; try { input = JSON.parse(raw); } catch { return { error: "Enter valid JSON.", result: null }; } // No catch here: an unexpected exception is not a validation result. // It leaves the action and reaches app/error.jsx. return { error: null, result: await run(input) }; } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useEffect } from "react"; export default function LabError({ error, reset }) { useEffect(() => { console.log("Unexpected failure:", error.message); }, [error]); return ( <main> <h1>Something went wrong on our side</h1> <p>This is not a problem with your input.</p> <button onClick={() => reset()}>Back to the form</button> </main> ); } "use client"; import { useActionState } from "react"; import { evaluate } from "./actions.js"; export default function ProbeForm({ initial }) { const [state, action, pending] = useActionState(evaluate, { error: null, result: null, }); return ( <form action={action}> <label> Input JSON{" "} <textarea name="input" defaultValue={JSON.stringify(initial)} rows={3} /> </label> <button disabled={pending}>{pending ? "Evaluating…" : "Evaluate"}</button> <p role="alert">{state.error}</p> <pre role="status"> {state.result === null ? "" : JSON.stringify(state.result)} </pre> </form> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ title, exists }) { if (!title.trim()) return { ok: false, code: "invalid_title" }; if (exists) return { ok: false, code: "duplicate_title" }; return { ok: true, title: title.trim() }; } export const examples = [ [ { title: "", exists: false }, { ok: false, code: "invalid_title" }, ], [ { title: "Forms", exists: true }, { ok: false, code: "duplicate_title" }, ], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input {"title": "", "exists": false} → {"ok": false, "code": "invalid_title"}.
  • Input {"title": "Forms", "exists": true} → {"ok": false, "code": "duplicate_title"}.

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

The failure to avoid

Returning either a record, a string or undefined makes every caller guess. The opposite mistake is just as common: wrapping the whole action in try/catch and turning every exception into a friendly form message.

app/actions.js in this lab parses the JSON you type and calls run. It has no catch around run on purpose:

JavaScript
export async function evaluate(previous, formData) {
  // …parse the JSON, returning { error } if it isn't JSON…
  // No catch here: an unexpected exception is not a validation result.
  // It leaves the action and reaches app/error.jsx.
  return { error: null, result: await run(input) };
}

Predict

Type {} into the lab's Input JSON box and press Evaluate. run destructures title from it. What happens, and what does the console show?

Check your prediction

title is undefined, so title.trim() throws Cannot read properties of undefined (reading 'trim'). The exception leaves the action, and Next.js shows app/error.jsx: Something went wrong on our side, with the real message in the console. That's right for this input: {} isn't a title the user typed badly, it's a request the form can never send, so it points to a bug or a misbehaving client.

Had the action ended in a catch returning a message such as That input could not be evaluated., the same bug would look like a validation message, nothing would be logged, and an outage in a real database call would look like bad input too.

Trace {"title": " ", "exists": true}. Which code comes back, and why does the order of the two checks matter to the person filling in the form?

Exercise

Extend the contract

Include a field name of title on expected failures so the form can associate an error with its input.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"title": "", "exists": false} must return {"ok": false, "code": "invalid_title", "field": "title"}.
Your working space Next.js · 8 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import ProbeForm from "./ProbeForm.jsx"; import { examples } from "@/lib/contract.js"; import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Expected Failures Have a Result Shape</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <ProbeForm initial={examples[0][0]} /> <Cases /> </main> ); } "use server"; import { run } from "@/lib/contract.js"; export async function evaluate(previous, formData) { const raw = formData.get("input"); if (typeof raw !== "string") return { error: "Enter JSON.", result: null }; let input; try { input = JSON.parse(raw); } catch { return { error: "Enter valid JSON.", result: null }; } // No catch here: an unexpected exception is not a validation result. // It leaves the action and reaches app/error.jsx. return { error: null, result: await run(input) }; } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useEffect } from "react"; export default function LabError({ error, reset }) { useEffect(() => { console.log("Unexpected failure:", error.message); }, [error]); return ( <main> <h1>Something went wrong on our side</h1> <p>This is not a problem with your input.</p> <button onClick={() => reset()}>Back to the form</button> </main> ); } "use client"; import { useActionState } from "react"; import { evaluate } from "./actions.js"; export default function ProbeForm({ initial }) { const [state, action, pending] = useActionState(evaluate, { error: null, result: null, }); return ( <form action={action}> <label> Input JSON{" "} <textarea name="input" defaultValue={JSON.stringify(initial)} rows={3} /> </label> <button disabled={pending}>{pending ? "Evaluating…" : "Evaluate"}</button> <p role="alert">{state.error}</p> <pre role="status"> {state.result === null ? "" : JSON.stringify(state.result)} </pre> </form> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ title, exists }) { if (!title.trim()) return { ok: false, code: "invalid_title" }; if (exists) return { ok: false, code: "duplicate_title" }; return { ok: true, title: title.trim() }; } export const examples = [ [ { title: "", exists: false }, { ok: false, code: "invalid_title" }, ], [ { title: "Forms", exists: true }, { ok: false, code: "duplicate_title" }, ], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

The form needs to know which input an error belongs to, for every expected failure. That's one more stable property of the failure shape, not a new kind of result.

Hint 2: a first step

Both failure branches need the same added property. Keep the success result unchanged.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run({ title, exists }) {
  if (!title.trim())
    return { ok: false, code: "invalid_title", field: "title" };
  if (exists) return { ok: false, code: "duplicate_title", field: "title" };
  return { ok: true, title: title.trim() };
}

Both failures concern the title, so both carry field: "title", and the form can put the message next to that input and mark it with aria-invalid. The success shape doesn't change, so callers that check ok first keep working. A field name is better than a sentence because the wording can change without breaking the form.

Explain it without the code

Name one failure the Library form should show as a result, and one it should leave to error.jsx. Write what makes them different.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.