Error Formatting

You can do custom error formatting in your router and the returned object will be inferred all the way to your client (& React components)

Working example#

Usage example highlighted#

Adding custom formatting#

const router = trpc.router<Context>()
.formatError(({ defaultShape, error }) => {
return {
...defaultShape,
zodError:
error.code === 'BAD_USER_INPUT' &&
error.originalError instanceof ZodError
? error.originalError.flatten()
: null,
};
})

Usage in React#

function MyComponent() {
const mutation = trpc.useMutation('addPost');
useEffect(() => {
mutation.mutate({ title: 'example' });
}, []);
if (mutation.error?.shape?.zodError) {
// zodError will be inferred
return (
<pre>Error: {JSON.stringify(mutation.error.shape.zodError, null, 2)}</pre>
);
}
return <>[...]</>;
}

All properties sent to formatError()#

{
error: TRPCError;
type: ProcedureType | 'unknown';
path: string | undefined;
input: unknown;
ctx: undefined | TContext;
defaultShape: DefaultErrorShape; // the default error shape
}

DefaultErrorShape:

export type DefaultErrorShape = {
message: string;
code: string;
path?: string;
stack?: string; // will be set if `process.env.NODE_ENV !== 'production'`
};