Last Updated: February 25, 2016
·
1.877K
· teddy

Stack Trace for JavaScript

Errors in JavaScript can often be cryptic and fatal. Combined with callbacks, asynchronous-ness, and common functions, finding the root cause can be hell.

Better error handling can be achieved using the .stack call on an error within the catch block of a function. All errors can be captured by creating a function called window.onerror.

For example:

body onload="func()">
<div id="error"></div>
<div id="error2"></div>
</body>

<script type="text/javascript">

function func()
{
    try
    {
        var abc;
        console.log(abc.doesnt_exist)
    }
    catch (error)
    {
        document.getElementById('error').innerText = error.stack;
    }

    abc.doesnt_exist
}

window.onerror = function(message, url, linenumber) 
{
  document.getElementById('error2').innerText = "JavaScript error: " + message + " on line " + linenumber + " for " + url;
}

</script>

The code is executed on load, and is purposely designed to fail. This will fail in two places when calling the .doesnt_exist method, which is a method with no definition. One within the try...catch block, which will populate the first error message, and one without, which will be caught by the window.onerror.

TypeError: Cannot read property 'doesnt_exist' of undefined
at func (file:///Z:/Teddy/websites/Echovoice%20Sandbox/javascript%20stack%20trace/stack.html:22:18)
at onload (file:///Z:/Teddy/websites/Echovoice%20Sandbox/javascript%20stack%20trace/stack.html:7:108)
JavaScript error: Uncaught TypeError: Cannot read property 'doesnt_exist' of undefined on line 29 for file:///Z:/Teddy/websites/Echovoice%20Sandbox/javascript%20stack%20trace/stack.html

The output will show the line number and function calls for each method.