エラーフォーマット
非公式ベータ版翻訳
このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →
ルーターで定義したエラーフォーマットはクライアント側(& React コンポーネント)まで型安全に伝播します
使用例のハイライト
カスタムフォーマットの追加
server.tstsimport { 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.tstsimport { 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.tsxtsxexport function MyComponent() {const mutation = trpc.addPost.useMutation();useEffect(() => {mutation.mutate({ title: 'example' });}, []);if (mutation.error?.data?.zodError) {// zodError will be inferredreturn (<pre>Error: {JSON.stringify(mutation.error.data.zodError, null, 2)}</pre>);}return <>[...]</>;}
components/MyComponent.tsxtsxexport function MyComponent() {const mutation = trpc.addPost.useMutation();useEffect(() => {mutation.mutate({ title: 'example' });}, []);if (mutation.error?.data?.zodError) {// zodError will be inferredreturn (<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:
tsinterface DefaultErrorData {code: TRPC_ERROR_CODE_KEY;httpStatus: number;path?: string;stack?: string;}interface DefaultErrorShapeextends TRPCErrorShape<TRPC_ERROR_CODE_NUMBER, DefaultErrorData> {message: string;code: TRPC_ERROR_CODE_NUMBER;}
tsinterface DefaultErrorData {code: TRPC_ERROR_CODE_KEY;httpStatus: number;path?: string;stack?: string;}interface DefaultErrorShapeextends TRPCErrorShape<TRPC_ERROR_CODE_NUMBER, DefaultErrorData> {message: string;code: TRPC_ERROR_CODE_NUMBER;}