Aller au contenu principal
Version : 9.x

Formatage des erreurs

Traduction Bêta Non Officielle

Cette page a été traduite par PageTurner AI (bêta). Non approuvée officiellement par le projet. Vous avez trouvé une erreur ? Signaler un problème →

Le formatage des erreurs dans votre routeur sera propagé jusqu'à votre client (et aux composants React)

Exemple d'utilisation mis en avant

Ajout d'un formatage personnalisé

server.ts
ts
const 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.ts
ts
const 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,
},
};
});

Utilisation avec React

components/MyComponent.tsx
tsx
export function MyComponent() {
const mutation = trpc.useMutation('addPost');
useEffect(() => {
mutation.mutate({ title: 'example' });
}, []);
if (mutation.error?.data?.zodError) {
// zodError will be inferred
return (
<pre>Error: {JSON.stringify(mutation.error.data.zodError, null, 2)}</pre>
);
}
return <>[...]</>;
}
components/MyComponent.tsx
tsx
export function MyComponent() {
const mutation = trpc.useMutation('addPost');
useEffect(() => {
mutation.mutate({ title: 'example' });
}, []);
if (mutation.error?.data?.zodError) {
// zodError will be inferred
return (
<pre>Error: {JSON.stringify(mutation.error.data.zodError, null, 2)}</pre>
);
}
return <>[...]</>;
}

Toutes les propriétés envoyées à formatError()

Depuis la version v8.x, tRPC est conforme à 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
interface DefaultErrorData {
code: TRPC_ERROR_CODE_KEY;
httpStatus: number;
path?: string;
stack?: string;
}
interface DefaultErrorShape
extends TRPCErrorShape<TRPC_ERROR_CODE_NUMBER, DefaultErrorData> {
message: string;
code: TRPC_ERROR_CODE_NUMBER;
}
ts
interface DefaultErrorData {
code: TRPC_ERROR_CODE_KEY;
httpStatus: number;
path?: string;
stack?: string;
}
interface DefaultErrorShape
extends TRPCErrorShape<TRPC_ERROR_CODE_NUMBER, DefaultErrorData> {
message: string;
code: TRPC_ERROR_CODE_NUMBER;
}