A JavaScript Error object represents a failed operation while carrying information for both recovery and diagnosis. The language guarantees little beyond properties such as message and name; runtimes commonly add stack traces, codes, and hidden state. section 7.0 section 7.1
Do not confuse an Error object with an error value. JavaScript permits throwing strings, numbers, null, undefined, or arbitrary objects, although modern practice standardizes on throwing Error instances. A catch handler therefore cannot assume standard properties unless the surrounding code establishes that convention. section 7.2
Treat the object as a boundary between machine recovery and human debugging:
- Use the error category or code to choose whether to retry, fall back, or stop; use message and stack for diagnosis. section 7.1 section 7.3
- Avoid matching human-readable messages for control flow. Node.js error codes such as ENOENT, EACCES, and EMFILE provide more stable recovery signals. section 7.3
- Remember that stack capture is not free: engines retain structured call frames when constructing an Error, and formatting occurs when stack is read. section 7.4.1 section 7.4.2
- Reduce diagnostic overhead deliberately in high-volume paths; V8 exposes the non-standard Error.stackTraceLimit setting, while deeper call stacks still increase capture cost. section 7.4.2
A catch value is not automatically an Error
A handler that reads e.message or e.stack is safe only when callers follow the Error-object convention. Arbitrary thrown values remain valid JavaScript, so boundaries may need to normalize or classify the caught value before using diagnostic properties. section 7.2
try {
await someOperation();
} catch (e) {
switch(e.code) {
case 'ENOENT':
// File not found - maybe create it
break;
case 'EACCES':
// Permission denied - fatal
throw e;
case 'EMFILE':
// Too many open files - retry later
await delay(100);
return retry();
}
}This Node.js example demonstrates switching on stable machine-readable codes while reserving messages for human diagnosis. section 7.3
