Applied AI-Accelerated Government Development

Mutations with Visible Failure

Updated

Intermediate

What you'll learn

~25 min
  • Route every read and write through shared fetchers that turn the error contract from Lesson 7 into a thrown, readable error
  • Show visible feedback for each mutation outcome with a snackbar (a brief, dismissible status message), including the failure case
  • Apply an optimistic update (show the change before the server confirms it) with an automatic rollback, and know when not to
  • Prove with a test that a failed write is visible and that no empty catch block exists

A click must always answer

A user presses Save. Either the app tells them it worked, or it tells them why it did not. The failure to avoid is the third outcome: nothing visible happens, they press again, and a support ticket arrives that says “the app is broken” when the real cause was an expired session.

You will build the pattern for the feature from Lesson 6: reads through one shared fetcher, writes through one shared mutation fetcher, and a feedback rule that covers every outcome. The reference app implements it with SWR (a React data-fetching library, useSWR for reads and useSWRMutation for writes). The pattern is the lesson; the library is one way to carry it.

ProblemThe patternWhere your platform lesson lands itYou decide
Where fetching and error parsing liveShared fetchers imported by every hook (SWR here; TanStack Query or Server Functions with useActionState carry the same pattern)Nothing platform-specific: the fetchers read the errors-as-a-contract body from Lesson 7Which one client-side data layer your teams standardize on
How a write reports backSnackbar on success and on error; an inline form error for validation failuresNothing platform-specificWhich outcomes get a toast and which get inline text
When the UI changesOptimistic for low-risk toggles, confirmed for the restNothing platform-specificWhich actions are safe to show before they are confirmed
What counts as handledEvery catch surfaces a message, backed by a global error boundaryNothing platform-specific; the no-empty-catch test and the Playwright abort test run in the pipeline 37 lands on your code hostHow a failure reaches the user when no component caught it

Plan the change with your agent

Open your workspace agent at the project root with the vehicle-fleet feature from Lesson 6 in place, switch to Plan mode (Shift+Tab, /plan, or the desktop app’s mode picker), and ask:

Read src/lib/response.ts and our vehicle-fleet feature, and plan a shared SWR data layer and mutation feedback so every write surfaces success or a readable error message. Ask me anything unclear before writing code.

What to check in the plan before you approve

  • src/lib/swr-helpers.ts exports listFetcher(url) and mutationFetcher(url, { arg }), parsing !res.ok bodies from Lesson 7’s error contract into a thrown Error and falling back cleanly when a proxy returns non-JSON text.
  • src/hooks/useVehicleFleet.ts uses useSWR for the list and useSWRMutation for create, update, and remove, sending item requests to ${url}/${id}.
  • src/app/(protected)/vehicle-fleet/FleetTable.tsx uses a shared useFeedback() hook (Snackbar with an Alert of role="alert" for errors), makes the status toggle optimistic with automatic rollback on failure, and keeps delete non-optimistic behind a confirmation dialog.
  • No empty catch blocks, no console.log-only error handling, and no direct fetch() calls in components.

If the agent’s initial plan makes delete optimistic or leaves errors only in the console, push back before approving:

Make the status toggle optimistic with automatic rollback on error, but keep delete non-optimistic behind a confirmation dialog.

What you get

SESSION Mutation feedback: plan, build, break on purpose, fix
  1. Typed in the terminal: claude
  2. Mode:Plan mode
  3. You type in the session: Read src/lib/response.ts and our vehicle-fleet feature, and plan a shared SWR data layer and mutation feedback so every write surfaces success or a readable error message. Ask me anything unclear before writing code.
  4. The tool replies: Proposed plan: 1. src/lib/swr-helpers.ts: listFetcher and mutationFetcher that parse the Lesson 7 error envelope and throw an Error. 2. src/hooks/useVehicleFleet.ts: useSWR for the list and useSWRMutation for create, update, and remove. 3. src/app/(protected)/vehicle-fleet/FleetTable.tsx: shared useFeedback() Snackbar+Alert hook and handlers that notify on both success and failure. Which mutations should update optimistically before the server responds?
  5. You type in the session: Make the status toggle optimistic with automatic rollback on error, but keep delete non-optimistic behind a confirmation dialog. Build it.
  6. The tool replies: Created src/lib/swr-helpers.ts, src/hooks/useVehicleFleet.ts and FleetTable.tsx. - listFetcher and mutationFetcher both throw an Error carrying the contract's message; a body that is not JSON falls back to 'Request failed'. - useFeedback() holds one Snackbar plus Alert for the whole page; errors use severity error. - create, update and remove each notify on success and in catch. - The status toggle passes optimisticData to trigger, so a rejected write rolls the row back automatically. I notify in both branches. - Delete opens a confirmation dialog and waits for the server. I left no empty catch and no direct fetch in the component.
  7. You type in the session: Simulate a 403 from the update route. What does the user see, and what does the row do?
  8. The tool replies: The fetcher parses the contract body, so the thrown message is the server's text, for example 'Your session has expired. Sign in again.' The catch calls notify(message, 'error') and the Alert is announced to assistive technology because it has role alert. For the optimistic toggle, SWR restores the previous row when the mutation throws, so the grid shows the old status and the snackbar explains why. Nothing is swallowed.
  9. You type in the session: The server returns an HTML error page from a proxy in front of the app. What does the user see?
  10. The tool replies: Good catch. res.json() would throw a SyntaxError and the user would see 'Unexpected token <'. I changed both fetchers to read the body as text, try to parse JSON, and fall back to 'Request failed (status 502)' when the body is not JSON. A raw parser message never reaches the snackbar.
  11. You type in the session: Now add a test that fails if anyone adds an empty catch.
  12. The tool replies: Created src/lib/no-empty-catch.test.ts. It walks src and fails on any catch block whose body is empty or contains only a comment, and names the file and line. I planted one in FleetTable.tsx, saw the failure, and removed it. I also added a Playwright test that aborts the update request and expects an alert to appear.

Illustrative session; exact output varies by tool and agency configuration.


The shared fetchers

Five developers writing five modules handle errors five ways: one swallows them, one prints [object Object], one forgets the content type. A shared fetcher does it once.

REFERENCE CODE src/lib/swr-helpers.ts: shared list and mutation fetchers parsing the error contract open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
src/lib/swr-helpers.ts
async function readError(res: Response): Promise<string> {
try {
const body = await res.json();
return body?.error?.message ?? `Request failed (status ${res.status})`;
} catch {
return `Request failed (status ${res.status})`; // body was not JSON
}
}
export const listFetcher = async (url: string) => {
const res = await fetch(url);
if (!res.ok) throw new Error(await readError(res));
return (await res.json()).data;
};
export const mutationFetcher = async (
url: string,
{ arg }: { arg: { method: string; id?: number; body?: unknown } },
) => {
// Lesson 7: create goes to /api/vehicle-fleet; read, update and delete go to /api/vehicle-fleet/[id]
const res = await fetch(arg.id === undefined ? url : `${url}/${arg.id}`, {
method: arg.method,
headers: { "Content-Type": "application/json" },
body: arg.body === undefined ? undefined : JSON.stringify(arg.body),
});
if (!res.ok) throw new Error(await readError(res));
return res.json();
};

The catch in readError is not empty: it returns a message. That distinction is the rule.

REFERENCE CODE src/hooks/useVehicleFleet.ts: SWR read and mutation hook for the vehicle-fleet feature open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
src/hooks/useVehicleFleet.ts
import useSWR from "swr";
import useSWRMutation from "swr/mutation";
import { listFetcher, mutationFetcher } from "@/lib/swr-helpers";
export function useVehicleFleet() {
const list = useSWR("/api/vehicle-fleet", listFetcher);
const write = useSWRMutation("/api/vehicle-fleet", mutationFetcher);
return {
...list,
create: (body: unknown) => write.trigger({ method: "POST", body }),
update: (body: unknown, opts?: Parameters<typeof write.trigger>[1]) =>
write.trigger({ method: "PUT", id: (body as { id: number }).id, body }, opts),
remove: (id: number) => write.trigger({ method: "DELETE", id }),
};
}

useSWRMutation throws from trigger by default and revalidates the key on success, so the list refreshes without a hand-written call.


Feedback on every outcome

Here is a reference excerpt of how your agent wires useFeedback() into a mutation handler in FleetTable.tsx:

// FleetTable.tsx (excerpt)
const { notify, node } = useFeedback();
async function handleCreate(form: VehicleInput) {
try {
await create(form);
notify("Vehicle added", "success");
} catch (err) {
notify(err instanceof Error ? err.message : "Failed to add vehicle", "error");
}
}

Every try has a catch, and every catch tells the user something. An empty catch turns a 403 caused by an expired session into a mystery.

⚠Empty catch blocks are the failure mode this lesson exists for

A console.error alone is also silent, because the user is not reading the console. Log if you need a record, but always surface the message too.


Optimistic updates, and when not to

An optimistic update shows the change before the server confirms it, then restores the old value if the write fails. SWR supports it directly on trigger, with rollback on error enabled by default:

REFERENCE CODE FleetTable.tsx (excerpt): optimistic status toggle with automatic rollback on failure open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
async function handleStatusToggle(v: VehicleRow) {
const next = v.status === "active" ? "inactive" : "active";
try {
await update(
{ id: v.id, status: next },
{
optimisticData: (current?: VehicleRow[]) =>
current?.map((r) => (r.id === v.id ? { ...r, status: next } : r)) ?? [],
},
);
notify("Status updated", "success");
} catch (err) {
// SWR has already rolled the row back; tell the user why.
notify(err instanceof Error ? err.message : "Failed to update status", "error");
}
}

Use it for reversible, frequent, low-stakes actions: a status toggle, an inline edit, a reorder. Do not use it for a delete or for anything that starts downstream work. Those wait for the server, behind a confirmation dialog.

ℹOther ways to carry the same pattern

TanStack Query offers the same shape with useMutation and its onError, onSuccess and optimistic-update hooks. React itself offers a built-in route in the pinned major: a Server Function called through useActionState, which returns the action’s result for you to render as feedback. Whichever you pick, a Server Function is its own entry point, so it must re-check the session and role itself, as in Lesson 3. The contract below does not change: every outcome of every write is visible.


Prove it

Two checks. The first is static, the second drives the browser.

REFERENCE TEST src/lib/no-empty-catch.test.ts: static check failing on empty catch blocks open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
src/lib/no-empty-catch.test.ts
import { it, expect } from "vitest";
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
const walk = (d: string): string[] =>
readdirSync(d).flatMap((n) => {
const p = join(d, n);
return statSync(p).isDirectory() ? walk(p) : [p];
});
it("no catch block is empty", () => {
const offenders = walk("src")
.filter((f) => /\.(ts|tsx)$/.test(f) && !f.endsWith(".test.ts"))
.filter((f) => /catch\s*(\([^)]*\))?\s*\{\s*(\/\/[^\n]*\s*)*\}/.test(readFileSync(f, "utf8")));
expect(offenders).toEqual([]);
});

And here is the reference Playwright test in tests/e2e/mutation-failure.spec.ts that your agent generates to verify the error alert appears in the browser:

tests/e2e/mutation-failure.spec.ts
import { test, expect } from "@playwright/test";
test("a failed update is visible", async ({ page }) => {
await page.route("**/api/vehicle-fleet/*", (route) =>
route.request().method() === "PUT"
? route.fulfill({ status: 403, contentType: "application/json",
body: JSON.stringify({ error: { code: "FORBIDDEN", message: "Your session has expired. Sign in again." } }) })
: route.continue());
await page.goto("/vehicle-fleet");
await page.getByRole("button", { name: /toggle status/i }).first().click();
await expect(page.getByRole("alert")).toContainText("session has expired");
});

The static test catches a swallowed error that no one has triggered yet. The browser test proves the user-visible half. The negative case for both: plant an empty catch, or remove the notify from one handler, and confirm the matching test fails before you trust it.


KNOWLEDGE CHECK

After Save, the snackbar says 'Vehicle updated' but the grid still shows the old values. Which cause fits?

KNOWLEDGE CHECK

Which action is a poor fit for an optimistic update?


Key takeaway

Every write ends in a message the user can see, whether it succeeded or failed, and a test makes that a property of the codebase rather than of each developer’s habits. The next lesson asks where the data on the screen came from.

LEADERSHIP DECISION
Whether a visible outcome message is a release requirement for every write, with the test as the check.
PRACTITIONER ACTION
Run the mutation-message test and add the failure case for each write you own.
SUCCESS MEASURE
Contract or revenue risk: no silent failed write reaching a user as if it had succeeded.

Legend: LEADERSHIP DECISION = what a leader decides · PRACTITIONER ACTION = what the engineer does next · SUCCESS MEASURE = how you know, in calendar time, assessor-hours or cost, contract or revenue risk, or audit finding avoided

Search lessons