0Pricing
tRPC End-to-End Type Safe APIs · Lección

Formato de errores y mensajes de validación por campo

Personalice la estructura de los errores de tRPC y muestre a su cliente mensajes de validación claros para cada campo.

Formato de errores y mensajes de validación por campo es una lección gratuita de tRPC End-to-End Type Safe APIs en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de tRPC End-to-End Type Safe APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de tRPC End-to-End Type Safe APIs incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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.

Preguntas frecuentes

¿La lección «Formato de errores y mensajes de validación por campo» es gratis?

Sí — el texto completo de «Formato de errores y mensajes de validación por campo» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de tRPC End-to-End Type Safe APIs, actualiza a CoddyKit PRO. El curso de tRPC End-to-End Type Safe APIs incluye 4 lecciones en total.

¿Qué aprenderé en «Formato de errores y mensajes de validación por campo»?

Personalice la estructura de los errores de tRPC y muestre a su cliente mensajes de validación claros para cada campo. Practicas tRPC End-to-End Type Safe APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar tRPC End-to-End Type Safe APIs?

No se requiere experiencia previa. tRPC End-to-End Type Safe APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Formato de errores y mensajes de validación por campo»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de tRPC End-to-End Type Safe APIs?

Sí. Cada lección de tRPC End-to-End Type Safe APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Gestión adecuada de errores en tRPC
  2. Tipos de error personalizados
  3. Transformadores de datos para serialización
  4. Formato de errores y mensajes de validación por campo
← Volver a tRPC End-to-End Type Safe APIs