HTTP and APIs · Lesson 13 of 18
Validation and error handling
Separate client mistakes from server faults and return a stable error shape.
Input arrives from untrusted boundaries: body, query, params and headers. Validate at the boundary, producing known typed data or a 4xx response. Unexpected faults go to a central error handler that logs safe context and returns a generic 500.
Raw request
Parse
Validate
Business logic
Central error mapper
function validateTask(body) {
if (!body || typeof body.title !== "string") return { ok: false, status: 400, error: "title is required" }
const title = body.title.trim()
if (title.length < 2) return { ok: false, status: 422, error: "title is too short" }
return { ok: true, value: { title } }
}
console.log(validateTask({ title: " Learn Node " }))
console.log(validateTask({ title: "x" }).status)Use custom errors with status and code for expected cases such as NOT_FOUND, while programming errors remain 500. Keep one response shape such as { error: { code, message, details } }. Log a correlation or request ID rather than sensitive bodies.
Quick question
The database connection unexpectedly fails. Return?
Exercise
Write validateAge(value) returning ok for an integer from 18 to 120, otherwise invalid. Print ok invalid invalid.
Expected output: ok invalid invalid
function validateAge(value) {
}
console.log(validateAge(25), validateAge(17), validateAge("25"))Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.