错误格式化
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
你在路由器中定义的错误格式化将一路传递至客户端(包括 React 组件)
使用示例高亮
添加自定义格式化
server.tstsconst router = trpc.router<Context>().formatError(({ shape, error }) => {return {...shape,data: {...shape.data,zodError:error.code === 'BAD_REQUEST' && error.cause instanceof ZodError? error.cause.flatten(): null,},};});
server.tstsconst router = trpc.router<Context>().formatError(({ shape, error }) => {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.useMutation('addPost');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.useMutation('addPost');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 <>[...]</>;}
传递给 formatError() 的所有属性
从
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;}