エラーフォーマット
非公式ベータ版翻訳
このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →
ルーターで設定したエラーフォーマットはクライアント側まで完全に伝播されます。
使用例のハイライト
カスタムフォーマットの追加
server.tstsimport {initTRPC } from '@trpc/server';import {ZodError } from 'zod';export constt =initTRPC .create ({errorFormatter (opts ) {const {shape ,error } =opts ;return {...shape ,data : {...shape .data ,zodError :error .code === 'BAD_REQUEST' &&error .cause instanceofZodError ?error .cause .flatten (): null,},};},});
server.tstsimport {initTRPC } from '@trpc/server';import {ZodError } from 'zod';export constt =initTRPC .create ({errorFormatter (opts ) {const {shape ,error } =opts ;return {...shape ,data : {...shape .data ,zodError :error .code === 'BAD_REQUEST' &&error .cause instanceofZodError ?error .cause .flatten (): null,},};},});
Reactでの使用方法
components/MyComponent.tsxtsximport {useEffect } from 'react';import {trpc } from '../utils/trpc';export functionMyComponent () {constmutation =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.tsxtsximport {useEffect } from 'react';import {trpc } from '../utils/trpc';export functionMyComponent () {constmutation =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 <>[...]</>;}
errorFormatter()に渡される全プロパティ
tRPCはJSON-RPC 2.0仕様に準拠しています
tsinterfaceErrorFormatterOpts {error :TRPCError ;type : 'query' | 'mutation' | 'subscription' | 'unknown';path : string | undefined;input : unknown;ctx : unknown;shape : {message : string;code : number;data : unknown };}
tsinterfaceErrorFormatterOpts {error :TRPCError ;type : 'query' | 'mutation' | 'subscription' | 'unknown';path : string | undefined;input : unknown;ctx : unknown;shape : {message : string;code : number;data : unknown };}
DefaultErrorShape:
tstypeDefaultErrorData = {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;};interfaceDefaultErrorShape {message : string;code :TRPC_ERROR_CODE_NUMBER ;data :DefaultErrorData ;}
tstypeDefaultErrorData = {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;};interfaceDefaultErrorShape {message : string;code :TRPC_ERROR_CODE_NUMBER ;data :DefaultErrorData ;}