tRPC Error Handling: TRPCError and Error Formatters
On this page
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:
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:
| Code | HTTP status | Typical use |
|---|---|---|
BAD_REQUEST | 400 | Invalid input (Zod failures use this) |
UNAUTHORIZED | 401 | Not signed in |
FORBIDDEN | 403 | Signed in, not allowed |
NOT_FOUND | 404 | No such resource |
CONFLICT | 409 | Duplicate or version clash |
PRECONDITION_FAILED | 412 | Stale version on update |
UNPROCESSABLE_CONTENT | 422 | Valid shape, rejected by business rules |
TOO_MANY_REQUESTS | 429 | Rate limited |
INTERNAL_SERVER_ERROR | 500 | Anything 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:
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:
boom: t.procedure.query(() => {
throw new Error('connect ECONNREFUSED 10.0.0.5:5432');
}),Testing this with tRPC 11.23, the client received:
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: falseThe 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:
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:
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:5432Log 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:
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:
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;
},
},
},
});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.