Error middleware & result types
Design a central error handler and typed Result pattern; wrap async handlers to forward errors; return consistent error envelopes.
Error middleware & result types is a free TypeScript Academy lesson on CoddyKit. This is lesson 3 of 3. 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, and your progress syncs across the web and the CoddyKit app. The TypeScript Academy course includes 3 lessons in total.
Intro
Goal: Centralize runtime errors and return a consistent JSON “error envelope”. You will create a Result type, an async handler wrapper, and a robust error middleware.
- Discriminated Result<T,E>
- next(err) from async handlers
- Unknown→typed error mapping
Result type
Use a discriminated union for function results: { ok: true; value } or { ok: false; error }. Callers must handle both branches.
// Result pattern for services and controllers
export type Ok<T> = { ok: true; value: T }
export type Err<E> = { ok: false; error: E }
export type Result<T, E = string> = Ok<T> | Err<E>
export const ok = <T>(value: T): Ok<T> => ({ ok: true, value })
export const err = <E>(error: E): Err<E> => ({ ok: false, error })
// Example usage
async function getUserName(id: string): Promise<Result<string, "NOT_FOUND" | "DB">> {
if (id === "missing") return err("NOT_FOUND")
try { return ok("Ada") } catch { return err("DB") }
}Error envelope
Normalize unknown into a small, predictable envelope. Avoid leaking stack traces to clients.
// Canonical error envelope
export type ErrorEnvelope = {
error: string
code?: string
details?: unknown
}
export function mapError(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" } }
}Async wrapper + middleware
Wrap any async handler so rejections call next(err). The final error middleware formats JSON once.
import express, { Request, Response, NextFunction } from "express"
export const asyncHandler = <P, ResBody, ReqBody, Query>(fn: (req: Request<P, ResBody, ReqBody, Query>, res: Response<ResBody>, next: NextFunction) => Promise<unknown>) => {
return (req: Request<P, ResBody, ReqBody, Query>, res: Response<ResBody>, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(next)
}
}
export function errorMiddleware(err: unknown, _req: Request, res: Response, _next: NextFunction) {
const env = mapError(err)
const status = env.code === "NOT_FOUND" ? 404 : 500
res.status(status).json(env)
}
// Usage
// app.get("/", asyncHandler(async (req, res) => { throw new Error("boom") }))
// app.use(errorMiddleware)Routes + integration
Combine validation and error handling: validation returns 400 with details; other rejections are caught by the central middleware.
import express from "express"
import { z } from "zod"
import { asyncHandler, errorMiddleware } from "./errors"
const createUserSchema = z.object({ name: z.string().min(1) })
const app = express()
app.use(express.json())
app.post("/users", asyncHandler(async (req, res) => {
const parsed = createUserSchema.safeParse(req.body)
if (!parsed.success) {
res.status(400).json({ error: "Invalid body", details: parsed.error.format() })
return
}
res.status(201).json({ id: "u_1", name: parsed.data.name })
}))
app.use(errorMiddleware)
app.listen(3000, () => console.log("http://localhost:3000"))Tips
Tips:
- Log server-side details; return minimal client messages.
- Prefer typed Result in services and map to HTTP at the edge.
- Never swallow rejections—always call
next(err).
Async errors check
Quick check: Which pattern forwards async errors correctly?
Recap
Recap: Use a Result union for domain logic, wrap async handlers to call next, and format errors once in a final middleware.
Learn TypeScript with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 101
- Lessons
- 352
Frequently Asked Questions
Is the “Error middleware & result types” lesson free?
Yes — the full text of “Error middleware & result types” is free to read here on the web. 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. The TypeScript Academy course includes 3 lessons in total.
What will I learn in “Error middleware & result types”?
Design a central error handler and typed Result pattern; wrap async handlers to forward errors; return consistent error envelopes. 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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 3.
How long does the “Error middleware & result types” 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
- Router handlers, Request/Response typing
- Schema validation with zod & inference to TS
- Error middleware & result types