错误格式化
您路由器中的错误格式化将被推断到您的客户端(以及 React 组件)
突出显示的使用示例
添加自定义格式化
server.tsts
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.tsts
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.tsxtsx
export 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.tsxtsx
export 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
:
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;}