Formato de errores
Traducción Beta No Oficial
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
El formato de errores en tu router se propagará completamente hasta tu cliente (y componentes React)
Ejemplo de uso destacado
Agregar formato personalizado
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,},};});
Uso en 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 <>[...]</>;}
Todas las propiedades enviadas a formatError()
Desde
v8.xtRPC cumple con 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;}