JavaScript · Error Handling · Mid-Level · Best Practice
How do you preserve context when wrapping errors across layers (e.g. UI ← API client ← fetch)?
Short Interview Answer
Wrap with `new Error(msg, { cause: original })` or custom errors carrying codes; log with full cause chain without leaking sensitive details to users.
Detailed Explanation
Each layer should add domain context ('Failed to load invoice 123') while keeping the underlying cause for diagnostics. ES2022 `cause` chains support this. Map low-level failures to stable app error codes for UI. Avoid double-logging at every layer. Sanitize messages shown to users. In TypeScript, typed error results are an alternative to exceptions for expected failures — pick a convention per layer. Include request IDs for correlation.
Example
try {
await fetchInvoice(id);
} catch (err) {
throw new Error(`Failed to load invoice ${id}`, { cause: err });
}Interview Tip
Mention `cause` — modern and underused in interviews.
Common Mistake
Replacing the original error entirely and losing the stack/root reason.