Felformatering
Inofficiell Beta-översättning
Denna sida har översatts av PageTurner AI (beta). Inte officiellt godkänd av projektet. Hittade du ett fel? Rapportera problem →
Din routers felformatering kommer att följas hela vägen till din klient (& React komponenter)
Exempel på användning med markering
Lägga till anpassad formatering
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,},};},});
Användning i 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 <>[...]</>;}
Alla egenskaper som skickas till errorFormatter()
Sedan
v8.xföljer 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:
tstype 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;}
tstype 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;}