Table of contents
- 1. Description
- 2. Example
- 3. See also
Description
This non-standard property of Error objects offers a trace of which functions were called, in what order, from which line and file, and with what arguments. The stack string proceeds from the most recent calls to earlier ones, leading back to the original global scope call.
Each step will be separated by a newline, with the first part of the line being the function name (if not a call from the global scope), followed by the argument values converted to string in parentheses, then by an at (@) sign, the file location (except when the function is the error constructor as the error is being thrown), a colon, and, if there is a file location, the line number. (Note the Error object also possesses the fileName and lineNumber properties for retrieving these from the error thrown (but only the error, and not its trace).)
While an object (or array, etc.) will appear in the converted form "[object Object]", and as such cannot be evaluated back into the actual objects, scalar values can be retrieved (though it may be easier to use arguments.callee.caller.arguments, as could the function name be retrieved by arguments.callee.caller.name). "undefined" is listed as "(void 0)". Note that if string arguments are passed in with values such as "@", "(", ")" (or if in file names), you cannot easily rely on these for breaking the line into its component parts.
Example
The following HTML markup demonstrates the use of stack property.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>Stack Trace Example</title>
<body>
<script type="text/javascript">
function trace() {
try {
throw new Error("myError");
}
catch(e) {
alert(e.stack);
}
}
function b() {
trace();
}
function a() {
b(3, 4, "\n\n", undefined, {});
}
a("first call, firstarg");
</script>
Assuming the above markup is saved as C:\example.html on a Windows file system and is open in a browser it produces an alert message box with the following text:
Error("myError")@:0
trace()@file:///C:/example.html:9
b(3,4,"\n\n",(void 0),[object Object])@file:///C:/example.html:16
a("first call, firstarg")@file:///C:/example.html:19
@file:///C:/example.html:21