Monday, 10 September 2012

Debugging Javascript with Assert

I just put together a short video explaining my favorite new trick in JavaScript, using an Assertion function to call debugger at the correct point of failure.

I tend to spend my working hours at the moment writing large JavaScript systems, and while step debugging is great for eventually finding the cause of an error, it does take quite a lot of time to drill into a system to identify the bug.

In a large data driven system, I would think nothing of spending a hour or two finding the precise cause of an error.

Assert to the rescue...,true,"runDisplay:unable to find " + displayName);

Simply by asserting that my method parameters, or calculated variables, are the correct type / value, and calling debugger if the test fails, I can now identify the cause of a bug in under a minute. No matter how large the system.

Obviously you will want to reduce the overhead when the system is fully debugged and working, ie: in production, so simply prefix the assertion with a boolean condition. When set to false, the assertion will then never be evaluated.

JS.debug &&

That's all there is to it, a nice simple trick. But it will have a greater effect on your ability to debug and identify the cause of run-time failure than anything else I have ever seen.

The assert function itself is this:

                    // if you have got here, you have a serious error
                    // use stack trace to identify the cause
                throw new Error(message);

You can find it, and more here:

That pretty much gives you everything you need anyway, but have a look at the video for a little more explanation.

No comments:

Post a Comment