格式化错误与字段级验证反馈
自定义 tRPC 错误的结构,并向客户端清晰地呈现字段级验证消息。
格式化错误与字段级验证反馈 是 CoddyKit 上的免费 tRPC End-to-End Type Safe APIs 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 tRPC End-to-End Type Safe APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 tRPC End-to-End Type Safe APIs 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Format Errors?
You can throw and catch tRPC errors. But clients often need structured error data, especially field-level messages from validation, to show next to form inputs.
The errorFormatter Option
tRPC lets you customize the error shape globally with errorFormatter when initializing.
const t = initTRPC.create({
errorFormatter({ shape }) {
return shape;
},
});Detecting Zod Errors
When a Zod input fails, tRPC attaches it as the error cause. You can detect and expose it.
import { ZodError } from "zod";
errorFormatter({ shape, error }) {
const isZod = error.cause instanceof ZodError;
return { ...shape, data: { ...shape.data, isZod } };
}Adding Flattened Field Errors
Zod can flatten issues into a fieldErrors map that maps each field to its messages.
const zodError = error.cause instanceof ZodError
? error.cause.flatten().fieldErrors
: null;
return { ...shape, data: { ...shape.data, zodError } };What the Client Receives
The client now gets a structured object it can attach to form fields.
// e.g. { zodError: { email: ["Invalid email"] } }Reading Errors on the Client
Catch the error and read the formatted data.
try {
await client.signup.mutate(input);
} catch (err) {
const fields = err.data?.zodError;
// show fields.email next to the input
}HTTP Status Codes
The shape includes a code that maps to an HTTP status, useful for clients reacting to UNAUTHORIZED vs BAD_REQUEST.
// shape.data.code === "BAD_REQUEST"
// shape.data.httpStatus === 400Not Leaking Internals
Be careful: do not expose stack traces or internal messages in production. Format errors to reveal only safe, user-facing details.
Logging the Raw Error
Log the full error server-side for debugging while sending a sanitized version to the client.
errorFormatter({ shape, error }) {
console.error(error); // full detail in server logs
return shape; // safe shape to client
}Consistent Error Contract
A consistent error shape across all procedures means your frontend can handle errors with one reusable helper.
Reusing a Client Helper
Because every procedure shares the same error shape, write one helper that extracts fieldErrors and a top-level message for any failed call.
function parseError(err) {
return { fields: err.data?.zodError, message: err.message };
}Quick Check
Test your error formatting knowledge.
Recap
You learned to deliver great error feedback:
- errorFormatter customizes the error shape globally
- Detect ZodError causes and expose fieldErrors
- Log full detail server-side, send a sanitized shape to clients
Well-shaped errors make forms and clients dramatically easier to build.
常见问题解答
「格式化错误与字段级验证反馈」课时是免费的吗?
是的 — 「格式化错误与字段级验证反馈」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 tRPC End-to-End Type Safe APIs 课程的其余内容,请升级到 CoddyKit PRO。 tRPC End-to-End Type Safe APIs 课程共包含 4 节课。
「格式化错误与字段级验证反馈」这节课中我会学到什么?
自定义 tRPC 错误的结构,并向客户端清晰地呈现字段级验证消息。 你通过在浏览器中直接运行的动手代码来练习 tRPC End-to-End Type Safe APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 tRPC End-to-End Type Safe APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 tRPC End-to-End Type Safe APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「格式化错误与字段级验证反馈」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 tRPC End-to-End Type Safe APIs 课中编写并运行代码吗?
能。每节 tRPC End-to-End Type Safe APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 优雅地处理 tRPC 错误
- 自定义错误类型
- 用于序列化的数据转换器
- 格式化错误与字段级验证反馈