DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jason has posted 22 posts at DZone. View Full User Profile

Adding A Stack Trace To JavaScript Errors

04.07.2009
| 8547 views |
  • submit to reddit
        Basic example of adding a stack trace to JavaScript errors.

function trace(e, fn) { e.stackTrace = e.stackTrace || []; e.stackTrace.push(fn); return e; }

function d() { try { throw new Error("oh noes!"); } catch (e) { throw trace(e, "d"); } }
function c() { try { d(); } catch (e) { throw trace(e, "c"); } }
function b() { try { c(); } catch (e) { throw trace(e, "b"); } }
function a() { try { b(); } catch (e) { throw trace(e, "a"); } }

try
{
  a();
}
catch (e)
{
  alert("Error: " + e.message + "\r\n" + "Stack Trace: " + e.stackTrace.join("\r\nat "));
}