본문 바로가기
버전: 11.x

오류 형식 지정

비공식 베타 번역

이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →

라우터에서 정의한 오류 형식 지정은 클라이언트(& React 컴포넌트)까지 그대로 전달됩니다.

사용 예제 하이라이트

커스텀 형식 지정 추가하기

server.ts
ts
import { initTRPC } from '@trpc/server';
export const t = initTRPC.context<Context>().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';
export const t = initTRPC.context<Context>().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
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
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()로 전달되는 모든 속성

v8.x 버전부터 tRPC는 JSON-RPC 2.0을 준수합니다.

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

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;
}