tRPC End-to-End Type Safe APIs · Lezione

Formattazione degli errori e feedback di validazione a livello di campo

Personalizzi la struttura degli errori tRPC e mostri al client messaggi di validazione chiari a livello di campo.

Lezione 4 di 413 passaggi

Formattazione degli errori e feedback di validazione a livello di campo è una lezione tRPC End-to-End Type Safe APIs gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento tRPC End-to-End Type Safe APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso tRPC End-to-End Type Safe APIs include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Gratis per iniziare

Impara tRPC End-to-End Type Safe APIs con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
10
Lezioni
40

Domande Frequenti

La lezione «Formattazione degli errori e feedback di validazione a livello di campo» è gratuita?

Sì — il testo completo di «Formattazione degli errori e feedback di validazione a livello di campo» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso tRPC End-to-End Type Safe APIs, passa a CoddyKit PRO. Il corso tRPC End-to-End Type Safe APIs include 4 lezioni in totale.

Cosa imparerò in «Formattazione degli errori e feedback di validazione a livello di campo»?

Personalizzi la struttura degli errori tRPC e mostri al client messaggi di validazione chiari a livello di campo. Eserciti tRPC End-to-End Type Safe APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare tRPC End-to-End Type Safe APIs?

Non è richiesta alcuna esperienza precedente. tRPC End-to-End Type Safe APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Formattazione degli errori e feedback di validazione a livello di campo»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione tRPC End-to-End Type Safe APIs?

Sì. Ogni lezione tRPC End-to-End Type Safe APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Gestire gli errori tRPC in modo efficace
  2. Tipi di errore personalizzati
  3. Trasformatori di dati per la serializzazione
  4. Formattazione degli errori e feedback di validazione a livello di campo
← Torna a tRPC End-to-End Type Safe APIs