Glossary / Error objects
Error objects
JavaScript Error objects represent failures and carry a name, message, and usually a stack trace. Built-in subclasses such as TypeError, RangeError, SyntaxError, ReferenceError, and URIError describe broad failure categories. Errors can be thrown synchronously or used as Promise rejection reasons; in application code, rejecting/throwing actual Error instances gives consistent diagnostics and metadata.
Creating, catching, and preserving context
try {
parseConfiguration(text);
} catch (cause) {
throw new Error("Unable to load application configuration", { cause });
}
The cause option preserves an underlying error when adding contextual information. A stack trace is implementation-specific and not a stable format to parse. Error messages may contain file paths, tokens, query contents, or user data; sanitize logs and do not expose internal stack traces to end users. Do not branch on message wording when a stable error class or code can be used.
A catch should recover, translate to a boundary-specific result, add useful context, or safely report and rethrow. Catching and ignoring an error hides defects. Async functions reject with the thrown value; JavaScript technically permits rejection with any value, but Error objects provide stack/context and are the clearer convention.
Operational guidance
Preserve causes across service boundaries where possible. Log structured fields such as operation, correlation ID, error type, and safe context. Avoid duplicate logs at every layer; log once at the boundary that owns the response. Separate expected domain outcomes (which may be values) from exceptional failures.
Interview questions
- Why throw an Error instead of a string? Error carries a name, stack, cause, and consistent diagnostics.
- Is stack format standardized? No; treat it as diagnostic text, not a protocol.
- How add context without losing root cause? Wrap with an Error and preserve the original through
cause. - Should every catch log? No; log at the owning boundary to avoid duplicate/noisy reports.