본문으로 건너뛰기
버전: 11.x

오류 포맷팅

라우터의 오류 포맷팅은 클라이언트까지 추론됩니다.

강조된 사용 예시

사용자 정의 포맷팅 추가

server.ts
ts
import { initTRPC } from '@trpc/server';
import { ZodError } from 'zod';
 
export const t = initTRPC.create({
errorFormatter(opts) {
const { shape, error } = opts;
return {
...shape,
data: {
...shape.data,
zodError:
error.code === 'BAD_REQUEST' && error.cause instanceof ZodError
? error.cause.flatten()
: null,
},
};
},
});
server.ts
ts
import { initTRPC } from '@trpc/server';
import { ZodError } from 'zod';
 
export const t = initTRPC.create({
errorFormatter(opts) {
const { shape, error } = opts;
return {
...shape,
data: {
...shape.data,
zodError:
error.code === 'BAD_REQUEST' && error.cause instanceof ZodError
? error.cause.flatten()
: null,
},
};
},
});

React에서 사용

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

errorFormatter()에 전송되는 모든 속성

tRPC는 JSON-RPC 2.0에 준수합니다.

ts
interface ErrorFormatterOpts {
error: TRPCError;
type: 'query' | 'mutation' | 'subscription' | 'unknown';
path: string | undefined;
input: unknown;
ctx: unknown;
shape: { message: string; code: number; data: unknown };
}
ts
interface ErrorFormatterOpts {
error: TRPCError;
type: 'query' | 'mutation' | 'subscription' | 'unknown';
path: string | undefined;
input: unknown;
ctx: unknown;
shape: { message: string; code: number; data: unknown };
}

DefaultErrorShape:

ts
type DefaultErrorData = {
code: TRPC_ERROR_CODE_KEY;
httpStatus: number;
/**
* Path to the procedure that threw the error
*/
path?: string;
/**
* Stack trace of the error (only in development)
*/
stack?: string;
};
 
interface DefaultErrorShape {
message: string;
code: TRPC_ERROR_CODE_NUMBER;
data: DefaultErrorData;
}
ts
type DefaultErrorData = {
code: TRPC_ERROR_CODE_KEY;
httpStatus: number;
/**
* Path to the procedure that threw the error
*/
path?: string;
/**
* Stack trace of the error (only in development)
*/
stack?: string;
};
 
interface DefaultErrorShape {
message: string;
code: TRPC_ERROR_CODE_NUMBER;
data: DefaultErrorData;
}