Catalog My learning Blog
tRPC Course: Type-Safe APIs with TypeScript and React · Phase 2 · Lesson 5 · 5 min read

tRPC Error Handling: TRPCError and Error Formatters

On this page
  1. Throw TRPCError for expected failures
  2. What happens to unexpected errors
  3. Shape errors with an error formatter
  4. Log errors on the server
  5. Handle errors on the client
  6. Decide which errors to retry
  7. Check yourself

Throw TRPCError for expected failures

Some failures are part of normal life: a task doesn't exist, a title is already taken, the user isn't signed in. For these, throw a TRPCError with a code that says what went wrong:

JavaScript
import { TRPCError } from '@trpc/server';

if (titleTaken) {
  throw new TRPCError({ code: 'CONFLICT', message: 'A task with this title already exists' });
}

tRPC maps each code to an HTTP status, so proxies, logs and monitoring tools see sensible numbers:

CodeHTTP statusTypical use
BAD_REQUEST400Invalid input (Zod failures use this)
UNAUTHORIZED401Not signed in
FORBIDDEN403Signed in, not allowed
NOT_FOUND404No such resource
CONFLICT409Duplicate or version clash
PRECONDITION_FAILED412Stale version on update
UNPROCESSABLE_CONTENT422Valid shape, rejected by business rules
TOO_MANY_REQUESTS429Rate limited
INTERNAL_SERVER_ERROR500Anything unexpected

There are more codes, like PAYMENT_REQUIRED (402) and SERVICE_UNAVAILABLE (503), but these cover most apps. You can attach the original error with cause so logs keep the full story:

Code
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'Could not save task', cause: err });

What happens to unexpected errors

Anything thrown that isn't a TRPCError becomes INTERNAL_SERVER_ERROR. Here's the part that surprises people. Suppose the database is down:

JavaScript
boom: t.procedure.query(() => {
  throw new Error('connect ECONNREFUSED 10.0.0.5:5432');
}),

Testing this with tRPC 11.23, the client received:

YAML
isDev: true   -> INTERNAL_SERVER_ERROR | connect ECONNREFUSED 10.0.0.5:5432 | stack sent: true
isDev: false  -> INTERNAL_SERVER_ERROR | connect ECONNREFUSED 10.0.0.5:5432 | stack sent: false

The isDev setting, which defaults to true unless NODE_ENV is production, only controls whether the stack trace is sent. The original message goes to the client either way. Database errors, file paths and internal hostnames end up in the browser, which is useful to an attacker mapping your systems.

Shape errors with an error formatter

An error formatter runs on every error before it's sent. It's where you mask internals and add fields the client needs. This one does both:

TypeScript
const isProd = process.env.NODE_ENV === 'production';

const t = initTRPC.context<Context>().create({
  isDev: !isProd,
  errorFormatter({ shape, error }) {
    const masked = isProd && error.code === 'INTERNAL_SERVER_ERROR';
    return {
      ...shape,
      message: masked ? 'Something went wrong. Please try again.' : shape.message,
      data: {
        ...shape.data,
        fieldErrors:
          error.code === 'BAD_REQUEST' && error.cause instanceof z.ZodError
            ? (z.flattenError(error.cause).fieldErrors as Record<string, string[] | undefined>)
            : null,
      },
    };
  },
});

Now the database failure reaches the client as 500 Something went wrong. Please try again., while a deliberate CONFLICT keeps its helpful message. Validation errors gain a fieldErrors map like { title: ['Title is required'] }.

That map matters more than it looks. For a Zod failure, error.message is a JSON dump of every issue, which is not something to show a user. Forms should read fieldErrors instead.

The formatter's return type flows to the client, so fieldErrors is typed there too. The as Record<...> cast is needed because the formatter sees a generic ZodError with no known fields, so Zod types the map as {}, and the client couldn't read fieldErrors.title without it.

Log errors on the server

Masking the message for clients means you need the real one somewhere. Every adapter accepts an onError callback:

Code
createHTTPServer({
  router: appRouter,
  createContext,
  onError({ error, path, type }) {
    if (error.code === 'INTERNAL_SERVER_ERROR') {
      logger.error({ path, type, err: error.cause ?? error }, 'tRPC procedure failed');
    }
  },
});
// server log: boom connect ECONNREFUSED 10.0.0.5:5432

Log INTERNAL_SERVER_ERROR loudly, since those are bugs or outages. Expected codes like NOT_FOUND and BAD_REQUEST happen all day and usually only belong in metrics.

Handle errors on the client

On the client, failed calls reject with a TRPCClientError. The isTRPCClientError helper narrows it, and passing your router type gives you the formatted data:

TypeScript
import { isTRPCClientError } from '@trpc/client';
import type { AppRouter } from '../server/router';

try {
  await trpc.task.create.mutate({ title: '   ' });
} catch (e) {
  if (isTRPCClientError<AppRouter>(e)) {
    console.log(e.data?.code, e.data?.httpStatus, e.data?.fieldErrors);
    // BAD_REQUEST 400 { title: [ 'Title is required' ] }
  }
}

Branch on e.data.code, never on the message text. Messages change, and after masking they don't say much anyway.

Not every client error comes from your server. If the network drops or a proxy returns HTML, there's no tRPC error body, and e.data is undefined. That's why the code above uses e.data?..

Decide which errors to retry

TanStack Query, which you'll use on Day 9, retries failed queries three times by default. Retrying a NOT_FOUND or FORBIDDEN just wastes time. A small rule fixes that:

JavaScript
new QueryClient({
  defaultOptions: {
    queries: {
      retry: (count, err) => {
        const code = isTRPCClientError(err) ? err.data?.code : undefined;
        if (code && ['BAD_REQUEST', 'UNAUTHORIZED', 'FORBIDDEN', 'NOT_FOUND'].includes(code)) return false;
        return count < 3;
      },
    },
  },
});
TipWrite one test that throws a plain Error with a fake secret in its message and checks that the production client sees only the generic text. It's a cheap guard against someone changing the formatter later.

Check yourself

No. In tRPC 11, isDev: false only stops the stack trace from being sent. The original message of an unexpected error still reaches the client, so a database error like ECONNREFUSED 10.0.0.5:5432 would expose an internal address. Replace the message for INTERNAL_SERVER_ERROR in the error formatter, and log the real one with onError.

For Zod failures the message is a JSON list of issues, not user-friendly text. The formatter's fieldErrors map gives clean messages per field.

Codes that won't change on retry, such as BAD_REQUEST, UNAUTHORIZED, FORBIDDEN and NOT_FOUND. Network failures and INTERNAL_SERVER_ERROR may be worth a retry.

Those are expected outcomes of normal use, not bugs, so logging each one buries the real problems. Log INTERNAL_SERVER_ERROR (and downstream failures) loudly with the cause attached, and count the expected codes as metrics instead. Then an alert on errors means something is actually broken.

The request failed without a tRPC error body, for example because the network dropped, the server was down, or a proxy returned an HTML error page. There was nothing for tRPC to parse into data. That's why client code should use e.data?.code and treat a missing code as a network-level failure.