All jobs

Add API Error Handling to a tRPC App

Yes. An agent shapes your tRPC errors so Zod field errors reach the form and failed mutations show a message, not a console line, tests both, and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads how errors move today, from the procedure to the screen. In a tRPC app laid out like trpc/examples-next-prisma-starter, src/server/trpc.ts creates the router with superjson as transformer and an errorFormatter that returns shape unchanged, so a Zod failure reaches the client as a BAD_REQUEST whose message is the raw Zod issue list. src/pages/api/trpc/[trpc].ts has an onError hook that only logs when error.code is INTERNAL_SERVER_ERROR. On the client, src/pages/index.tsx submits the add-post form with addPost.mutateAsync inside a try whose catch writes console.error({ cause }, 'Failed to add post'), so a title longer than the max(32) in post.add's input schema, or an empty one, fails silently from the user's point of view. src/pages/post/[id].tsx does better: it renders NextError with postQuery.error.data?.httpStatus.

Then it changes the formatter. errorFormatter in trpc.ts returns shape with a data.zodError field that holds the flattened field errors when error.code is BAD_REQUEST and error.cause is a ZodError, and null otherwise, the shape tRPC's own documentation describes for form errors. Because zod is on the 4 line here, the agent uses the flatten helper that version exports (z.flattenError on 4, error.flatten() on 3) and checks the inferred client type still compiles with pnpm tsc. onError in [trpc].ts is widened to log every error with its code and path, so a NOT_FOUND from post.byId is visible in the server log without being treated as a crash.

On the client, index.tsx stops swallowing the error: the form reads addPost.error?.data?.zodError?.fieldErrors and renders the first message under the matching title or text field, shows addPost.error.message for any non-Zod failure, and keeps the $form.reset() on success. The inputs get aria-describedby pointing at their error text. [id].tsx is left as it is, since it already maps the error to a status page.

Then it tests both layers. In src/server/routers/post.test.ts, beside the existing add-and-get test, a new test calls caller.post.add({ title: '', text: '' }) and asserts the rejection is a TRPCError with code BAD_REQUEST and a ZodError cause, and a unit test of the formatter asserts zodError.fieldErrors.title is present; pnpm test-unit runs them under Vitest with dotenv/config, against the Postgres DATABASE_URL from .env. In playwright/smoke.test.ts, a test submits an empty title and waits for the field error text, next to the existing go-to-root and add-a-post tests; pnpm test-e2e runs it after pnpm build, the way main.yml does.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add API error handling to this tRPC and Next.js app. Read src/server/trpc.ts, src/server/context.ts, src/server/routers/_app.ts, src/server/routers/post.ts, src/server/routers/post.test.ts, src/pages/api/trpc/[trpc].ts, src/pages/index.tsx, src/pages/post/[id].tsx, src/utils/trpc.ts, vitest.config.mts, playwright/smoke.test.ts, .github/workflows/main.yml and package.json first. Change errorFormatter so BAD_REQUEST errors caused by a ZodError carry the flattened field errors under data.zodError, and widen onError to log every error with its code and path. In index.tsx, show field errors under the title and text inputs and a general message for other failures instead of console.error. Add a Vitest test that an invalid post.add input rejects with BAD_REQUEST and a ZodError cause, a unit test for the formatter, and a Playwright test that an empty title shows the field error. Run pnpm lint, pnpm tsc, pnpm test-unit and, after pnpm build, pnpm test-e2e with Postgres available, and open a pull request with the output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

The pull request changes src/server/trpc.ts, src/pages/api/trpc/[trpc].ts, src/pages/index.tsx, src/server/routers/post.test.ts and playwright/smoke.test.ts. Its description shows the error shape a client now receives for an invalid post.add, as JSON, and pastes the lint, type check, Vitest and Playwright output from the sandbox.

Testing runs on the push with its unit and e2e jobs, each against the Postgres service main.yml starts, so the new tests run where the old ones do.

Before merging, a reviewer checks that the zodError field is only populated for BAD_REQUEST so an internal error never leaks a validation structure, decides whether onError should forward to their error reporting rather than the console, and reads the rendered form once to confirm the error text sits where their design wants it.

Run it on every tRPC app that swallows mutation errors

A team with several tRPC apps starts one run per repository from its own server: one POST /o/{org}/sessions each, with that repository in resources and a request_id that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own initTRPC call and forms, so an app that already formats zodError gets only the client side and the tests, and one with React Hook Form gets the field errors wired into setError instead of rendered by hand.

After the merge, an automation on the Project with a github trigger on pull_request.opened and pull_request.synchronize and the prompt "for each new or changed mutation in src/server/routers, check that the page calling it renders its error and comment with the file and line if it only logs" keeps new forms honest. The trigger puts the pull request after the prompt; only pushes by an owner, member or collaborator fire it, never a fork's.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

The error path is the part of an app nobody exercises by hand, and here it fails quietly: the form clears nothing, shows nothing and writes one line to a console the user cannot see. The agent reads the formatter, the handler and the form together, changes all three so they agree on one shape, and proves it from both ends, with a Vitest test on the caller and a Playwright test on the rendered page, in its own sandbox with the Postgres the suite expects.

The type check matters as much as the tests: data.zodError is inferred into the client from the server's formatter, so a mistake there is a compile error in index.tsx, and pnpm tsc runs before the pull request opens. Every command and its output stays with the run, so a reviewer sees the green run without pulling the branch.

Frequently asked questions

Why flatten the ZodError in the formatter rather than on the client?

Because the formatter runs on the server where the ZodError instance exists, and what crosses the wire is JSON. tRPC's error shape has a data object for exactly this; putting zodError there once means every page gets typed field errors through inferRouterOutputs without parsing messages.

Does it change what post.byId returns for a missing post?

No. byId already throws a TRPCError with code NOT_FOUND, and [id].tsx already renders a status page from error.data.httpStatus. The widened onError now logs that case at its code instead of ignoring it, which is the only difference.

Will the Playwright test be flaky because it needs the database?

It needs the same database the existing add-a-post test needs, started by the postgres service in main.yml and prepared by pnpm prebuild. The new test only submits an empty title and waits for the error text, so it never writes a row.

Which Zod version does this assume?

The one in package.json, on the 4 line. The agent uses the flatten helper that version exports and runs pnpm tsc, so if the installed Zod shapes fieldErrors differently from the 3 line the type check says so before the pull request opens.

More tRPC jobs

The same job on other stacks

Keep reading