Defensive parsing and error envelopes
Build robust request handling: parse defensively, map all failures to a compact JSON error envelope, and avoid leaking internals.
Defensive parsing and error envelopes is a free TypeScript Academy lesson on CoddyKit — lesson 2 of 2. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 2 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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" } }
}Validate helper
Wrap schemas in a validate helper that returns a discriminated result. Handlers stay small and consistent.
import { z, type ZodTypeAny } from "zod"
export function validate<T extends ZodTypeAny>(schema: T, value: unknown) {
const r = schema.safeParse(value)
if (!r.success) {
return { ok: false as const, issues: r.error.format() }
}
return { ok: true as const, data: r.data as z.infer<T> }
}Defensive handler
Validate early; return 400 with issue details. Unexpected failures propagate to the error middleware as a 500 with the envelope.
import type { Request, Response, NextFunction } from "express"
import { z } from "zod"
import { validate } from "./validate"
import { toEnvelope, type ErrorEnvelope } from "./envelope"
const bodySchema = z.object({ email: z.string().email(), newsletter: z.boolean().default(false) })
export function subscribe(req: Request, res: Response<{ ok: true } | ErrorEnvelope>, next: NextFunction) {
const r = validate(bodySchema, req.body)
if (!r.ok) return res.status(400).json({ error: "Invalid body", details: r.issues })
try {
// pretend to persist
return res.status(201).json({ ok: true })
} catch (e) {
return next(e)
}
}
export function errorMiddleware(err: unknown, _req: Request, res: Response<ErrorEnvelope>, _next: NextFunction) {
const env = toEnvelope(err)
res.status(500).json(env)
}Common envelopes
Provide tiny helpers for common outcomes: 404/401 with stable code strings so clients can branch reliably.
export function notFound(resource: string): { status: 404; body: { error: string; code: string } } {
return { status: 404, body: { error: `${resource} not found`, code: "NOT_FOUND" } }
}
export function unauthorized(): { status: 401; body: { error: string; code: string } } {
return { status: 401, body: { error: "unauthorized", code: "UNAUTHORIZED" } }
}Logs vs response
Balance logs vs response: log the full error server-side (stack, request id, user id) but return a minimal envelope to the client. Consider rate limits and redaction for PII.
Envelope practice check
Quick check: How should validation errors be returned?
Recap
Recap: Validate inputs with safeParse, map failures to a compact envelope, and separate rich logs from minimal client responses.
Frequently asked questions
Is the “Defensive parsing and error envelopes” lesson free?
Yes — the full text of “Defensive parsing and error envelopes” is free to read here on the web, and the TypeScript Academy course includes 2 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Defensive parsing and error envelopes”?
Build robust request handling: parse defensively, map all failures to a compact JSON error envelope, and avoid leaking internals. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start TypeScript Academy?
No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 2, so you can start here or from the beginning and move at your own pace.
How long does the “Defensive parsing and error envelopes” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this TypeScript Academy lesson?
Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- zod/valibot schemas + inference
- Defensive parsing and error envelopes