Validation and error contracts
Local practice: Node.js 22.16.0 on Linux x64; proposed 26.13.1 baseline remains untested. Save each example separately as main.mjs in a disposable directory. No packages or external services required. HTTP examples bind only to loopback and shut down after a finite scenario. Static Node.js code, not verified ByteMind execution.
Check an allowlisted order shape
function validateOrder(value){ if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).length!==1||!Number.isInteger(value.quantity)||value.quantity<1||value.quantity>20) return false; return true;}function invalidOrder(){return {type:'https://example.test/problems/invalid-order',title:'Invalid order',status:422,detail:'quantity must be an integer from 1 to 20; no other fields allowed'};}for(const value of [{quantity:2},{quantity:'2'},{quantity:21},{quantity:1,admin:true}]) console.log(validateOrder(value));Run:
node main.mjsExpected stdout:
truefalsefalsefalseExit status: 0. Expected stderr: empty.
How it works
Check the shape and allowed fields before performing business actions. A syntactically valid but unacceptable order can return 422; malformed JSON can return 400. A problem-details response uses application/problem+json and may include type, title, status and detail. Keep the actual HTTP status consistent with the body status and avoid revealing internal paths, stack traces or credentials. The examples use an allowlisted one-field order contract and a fixed synthetic problem response; no real user input or storage.
Return problem details
import { createServer } from 'node:http';import { once } from 'node:events';async function withServer(handler, use) { const server = createServer({ headersTimeout: 2000, requestTimeout: 2000 }, handler); server.listen(0, '127.0.0.1'); await once(server, 'listening'); try { await use(`http://127.0.0.1:${server.address().port}`); } finally { await new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }); }}const localFetch = (url, options = {}) => fetch(url, { ...options, redirect: 'error', signal: options.signal ?? AbortSignal.timeout(2000)});function validateOrder(value){ if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).length!==1||!Number.isInteger(value.quantity)||value.quantity<1||value.quantity>20) return false; return true;}function invalidOrder(){return {type:'https://example.test/problems/invalid-order',title:'Invalid order',status:422,detail:'quantity must be an integer from 1 to 20; no other fields allowed'};}await withServer((q,r)=>{const problem=invalidOrder();r.statusCode=problem.status;r.setHeader('content-type','application/problem+json');r.end(JSON.stringify(problem));},async base=>{const r=await localFetch(base);console.log(r.status,r.headers.get('content-type'),(await r.json()).title);});Run:
node main.mjsExpected stdout:
422 application/problem+json Invalid orderExit status: 0. Expected stderr: empty.
Common mistake
Do not spread an entire client body into a domain object. Reject unexpected fields, wrong types and out-of-range numbers. Never expose raw exceptions as public detail.
Practice
Extend the validator to accept an optional note up to 40 characters. Specify what counts as a valid empty note and add boundary checks.
Further reading: Authoritative source 1 · Authoritative source 2. Internal reference routes remain proposed until repository discovery.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Validation and error contracts — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
Does JSON parsing validate business rules?
Which media type identifies JSON problem details?
What should a public error avoid?