Read stack traces without depending on their format
Quick answer
A stack trace provides diagnostic information about nested calls associated with an error. It can help locate where an exception originated and how execution reached that point.
How it works
Error.stack is widely implemented but its text and frame collection behavior are not a portable parsing contract. Start with the error name and message, then inspect the earliest relevant application frame. Async boundaries, optimization, source maps and wrappers can change the trace. Keep stable error codes or tagged results for program decisions; use stack for diagnostics. The examples check a frame name in the local V8 runtime and an explicit cause.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. No interactive debugger attached; actual ByteMind editor support is unverified.
(async () => {function validateQty(){throw new RangeError("quantity");}try{validateQty();}catch(err){console.log(err.name,err.message,typeof err.stack,err.stack.includes("validateQty"));}})()Expected console output:
RangeError quantity string trueThe local runtime includes the named frame; portable code must not require the same format.
Run in Node.js v22.16.0 as a CommonJS script. No interactive debugger attached; actual ByteMind editor support is unverified.
(async () => {const original=new TypeError("bad input");const wrapped=new Error("load failed",{cause:original});console.log(wrapped.message,wrapped.cause===original,wrapped.cause.name);})()Expected console output:
load failed true TypeErrorThe wrapper keeps both the higher-level message and the original error object.
Common mistakes
Do not depend on exact line numbers or the literal wording of a native error. Avoid returning internal stack traces to users.
Practice
Throw an error from a small nested function and identify the first application frame and its caller.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Read stack traces without depending on their format — Knowledge Check
Apply the concept and reason about local example output.
What should machine-level error classification depend on?
What can change which frames appear in an error trace?
Why retain an original error as cause?
What is the exact console output in Read stack traces without depending on their format example 1?
(async () => {function validateQty(){throw new RangeError("quantity");}try{validateQty();}catch(err){console.log(err.name,err.message,typeof err.stack,err.stack.includes("validateQty"));}})()What is the exact console output in Read stack traces without depending on their format example 2?
(async () => {const original=new TypeError("bad input");const wrapped=new Error("load failed",{cause:original});console.log(wrapped.message,wrapped.cause===original,wrapped.cause.name);})()