エラーの整形とフィールド単位のバリデーションフィードバック
tRPCエラーの形式をカスタマイズし、フィールド単位のわかりやすいバリデーションメッセージをクライアントに伝えます。
「エラーの整形とフィールド単位のバリデーションフィードバック」はCoddyKit上の無料tRPC End-to-End Type Safe APIsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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.
よくある質問
「エラーの整形とフィールド単位のバリデーションフィードバック」レッスンは無料ですか?
はい。「エラーの整形とフィールド単位のバリデーションフィードバック」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応の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を演習し、24時間対応の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エラーの適切な処理
- カスタムエラー型
- シリアライズ用データトランスフォーマー
- エラーの整形とフィールド単位のバリデーションフィードバック