Skip to main content
Version: 10.x

格式错误

路由中的错误格式将一直推断到你的客户端(和 React 组件)

¥The error formatting in your router will be inferred all the way to your client (& React components)

高亮的用法示例

¥Usage example highlighted

添加自定义格式

¥Adding custom formatting

server.ts
ts
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.ts
ts
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 中的用法

¥Usage in React

components/MyComponent.tsx
tsx
export function MyComponent() {
const mutation = trpc.addPost.useMutation();
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.addPost.useMutation();
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 <>[...]</>;
}

所有属性发送至 errorFormatter()

¥All properties sent to errorFormatter()

由于 v8.x tRPC 兼容 JSON-RPC 2.0

¥Since v8.x tRPC is compliant with 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;
}