Wednesday, May 31, 2006

Javascript Debugging Hint

Often times I feel like I have to be a cross between Gil Grisom and Sherlock Holmes when I'm trying to debug a javascript error. So I get very excited when I find a tool or technique to help me. So far my favorite tool is the Venkman javascript debugger, despite rumors that it crashes on some machines.

The other day a co-worker mentioned that enabling the script debugging in Internet Explorer allowed Visual Studio to debug javascript in your site. You can do this by going into IE > Tools > Iternet Options > Advanced and unchecking the "Disable Script Debugging (Internet Explorer)" option. This was very exciting, a way to debug javascript directly in the IDE. It still didn't get rid of those cryptic IE errors, but at least you would break in the IDE. If you want to get better error messages, use Venkman.

Anyway, back to the task at hand. I noticed the other day that Visual Studio's CallStack window works while debugging javascript. Let's perform an exercise to see how useful this could be. Suppose you have a javascript function that is called from several different places. If that function threw an error, the call stack information could help determine what called it. Take a look at this simple page:


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Test Page</title>
<script type="text/javascript">
function runtest1()
{
test(true);
}
function runtest2()
{
test(false);
}
function test(x)
{
if(x == false)
throw("New Error");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button"
onclick="javascript:runtest1();runtest2();"
value="Push Me" />
</div>
</form>
</body>
</html>


When you click on the button, runtest1 will execute successfully and runtest2 will throw an error. Now pretend that you don't know exactly where the error was coming from. Take a look at the stack trace and see if you can figure it out.

No comments: