Request Validation and Centralized Error Handling
Never trust input. Request validation checks body, params and query against a schema before your logic runs, and centralized error handling turns every failure into one consistent response. Both are standard parts of backend take-home reviews.
What you will learn
- Validate requests with a schema library such as Zod
- Return field-level validation errors with 422 or 400
- Map known errors to status codes in one handler
- Avoid leaking stack traces in production
Key concepts
Schema validation
Describe the expected shape once (types, lengths, formats). The library parses the input, strips unknown fields and returns typed data or a list of errors.
Allow-list, not block-list
Accept only the fields you expect. Passing req.body straight into an ORM create call lets a user set isAdmin: true (mass assignment).
Central error handler
One function that maps error types to responses, logs with the request id, and hides internal details from clients.
Step by step
A reusable validate middleware
import { z } from 'zod'
export const validate = (schema) => (req, res, next) => {
const result = schema.safeParse({ body: req.body, query: req.query, params: req.params })
if (!result.success) {
return res.status(422).json({
title: 'Validation failed',
errors: result.error.issues.map((i) => ({ field: i.path.slice(1).join('.'), message: i.message })),
})
}
req.valid = result.data
next()
}
const createUser = z.object({
body: z.object({ email: z.email(), name: z.string().min(2).max(60), password: z.string().min(8) }),
})
app.post('/users', validate(createUser), createUserHandler)Examples
The error handler
export function errorHandler(err, req, res, next) {
const status = err.status || 500
if (status >= 500) req.log.error({ err, reqId: req.id }, 'request failed')
res.status(status).json({
title: status >= 500 ? 'Something went wrong' : err.message,
code: err.code || 'INTERNAL',
requestId: req.id,
...(process.env.NODE_ENV !== 'production' && { stack: err.stack }),
})
}Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Add validation to a PATCH endpoint where every field is optional but at least one is required.
- Map a unique-constraint error from the database to 409 Conflict.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
Where should validation happen: frontend or backend?
Both, for different reasons. Frontend validation is for user experience. Backend validation is for correctness and security, because anyone can call your API directly.
What is mass assignment?
Copying all request fields into a model, so a user can set fields they should not (role, balance, isVerified). Prevent it by validating and picking only allowed fields.
Summary
Validate every input against a schema, accept only known fields, and handle all errors in one place with consistent JSON, a request id and no internal details in production.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus