0Pricing
tRPC End-to-End Type Safe APIs · Урок

Форматирование ошибок и обратная связь о проверке полей

Настройте структуру ошибок tRPC и выводите клиенту понятные сообщения о проверке на уровне отдельных полей.

«Форматирование ошибок и обратная связь о проверке полей» — бесплатный урок tRPC End-to-End Type Safe APIs на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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 === 400

Not 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/7) и разблокировать остальной курс 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/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать tRPC End-to-End Type Safe APIs?

Предыдущий опыт не требуется. tRPC End-to-End Type Safe APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Форматирование ошибок и обратная связь о проверке полей»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке tRPC End-to-End Type Safe APIs?

Да. Каждый урок tRPC End-to-End Type Safe APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Корректная обработка ошибок tRPC
  2. Пользовательские типы ошибок
  3. Преобразователи данных для сериализации
  4. Форматирование ошибок и обратная связь о проверке полей
← Назад к tRPC End-to-End Type Safe APIs