Error categories and propagation
Prerequisite: node-deterministic-test-isolation. Objective: Classify expected versus fatal error. Local baseline: Node.js 22.16.0 on Linux, ESM. Each example is independent: save as main.mjs in a disposable directory and run node main.mjs. The author harness uses a five-second timeout. Static snippets are not ByteMind interactive execution.
How it works
Use Error with a cause to preserve the original failure when adding context. Prefer stable documented error codes over matching human-readable messages. Promise failures propagate through await, whereas an EventEmitter error requires an appropriate listener or is thrown. Translate known domain errors to safe public responses at the boundary. Unknown faults must be observed and handled according to the integrity of the process; an uncaughtException handler is not a license to keep serving after corruption.
Preserve the cause while adding operation context
const original=Object.assign(new Error('synthetic read failed'),{code:'EIO'});try {try{throw original;}catch(cause){throw new Error('Catalog unavailable',{cause});}}catch(error){console.log(error.message);console.log(error.cause.code);console.log(error.cause===original);}Expected output:
Catalog unavailableEIOtrueThe wrapper preserves the original error for controlled diagnosis without exposing it in a public response.
Map known errors and unexpected errors differently
function publicError(e){switch(e.code){case 'NOT_FOUND':return {status:404,error:'not_found'};case 'CONFLICT':return {status:409,error:'conflict'};default:return {status:500,error:'internal_error'};}}for(const e of [{code:'NOT_FOUND'},{code:'CONFLICT'},new TypeError('synthetic detail')])console.log(JSON.stringify(publicError(e)));Expected output:
{"status":404,"error":"not_found"}{"status":409,"error":"conflict"}{"status":500,"error":"internal_error"}Only allowlisted domain errors get distinct public responses. The unexpected error detail is not serialized.
Common mistakes
Do not return a stack trace or raw underlying error to clients. Avoid swallowing unexpected faults by treating every exception as a 400 response.
Practice
Extend the error mapper with an explicit conflict code; leave unknown errors mapped to a generic server error.
Reference candidate: node-error-categories-and-propagation-lookup (route unverified). Documentation: https://nodejs.org/download/release/v22.16.0/docs/api/errors.html. Selected versioned documentation opened.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Error categories and propagation — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
Why set Error.cause?
How should an unknown internal fault appear to a client?
Can uncaughtException justify resuming unsafe process state?