0Pricing
TypeScript Academy · Lesson

Defensive parsing and error envelopes

Build robust request handling: parse defensively, map all failures to a compact JSON error envelope, and avoid leaking internals.

Intro

Goal: Parse defensively and always respond with a predictable JSON error envelope. We will keep validation near the boundary, standardize failures, and keep logs rich while responses are minimal.

  • safeParse on all untrusted inputs
  • Consistent { error, code, details? }
  • 4xx vs 5xx discipline

Envelope mapper

Define a tiny, reusable ErrorEnvelope. Map unknown errors to it without exposing stack traces.

export type ErrorEnvelope = { error: string; code?: string; details?: unknown }

export function toEnvelope(u: unknown): ErrorEnvelope {
  if (u instanceof Error) return { error: u.message }
  if (typeof u === "string") return { error: u }
  try { return { error: JSON.stringify(u) } } catch { return { error: "Unknown error" } }
}

All lessons in this course

  1. zod/valibot schemas + inference
  2. Defensive parsing and error envelopes
← Back to TypeScript Academy