Are you confident you are writing your JavaScript code error free? Do you wonder if traditional JavaScript error handling techniques still apply when developing for Windows Store apps? Does the Windows Library for JavaScript provide additional support for error handling? Do you deal with errors differently when writing asynchronous code? This entire post is dedicated to addressing these questions!

To Err is Human

Let’s be clear – if you were perfect and could write code that never fails, you would not need to read any further. For the rest of us (which is all of us), we must acknowledge that errors very often creep into code. Furthermore when developing with a language that is not strongly-typed such as JavaScript, there is potential for even more errors. Why? Consider the following code:

var x = 4;
// somewhere else in code...
x = "four";

The above code is valid. It showcases the dynamic nature of the language. However, it also illustrates the potential confusion as to what the variable x is. Any misuse of x based on assumptions could lead to buggy behaviors. One way to minimize these kind of issues is to be consistent with variable assignments with regard to inferred type. In other words, if a variable is assigned to a string, keep it a string.

Syntax errors are typically reported through Visual Studio when running the application in debug mode. However, the error message may not clearly state what is needed for correction. For example, observe the following syntax error:

varr x = 4;

Isolated from all other lines of code, it is easy to see that the keyword var was misspelled. Yet the IDE reports the error at runtime this way:

An entry level scripter could debate that there is a ‘;’ at the end of the line, and rationalize the error message itself is erroneous. The moral of the story here is to examine the complete line of code and surrounding context for discrepancies when the reported error message is not clear.

For web developers who are bringing their JavaScript skills over to Windows Store app development, the use of try…catch…finally statements are fully supported and should be used when attempting to execute any line of code that is conditional to a successful outcome – such as accessing external resources.

Mistrust is a Virtue

I find it a little humorous that the uninitialized use of WinJS.log (a method for logging error information among other things) will cause an error to be thrown at runtime. The log method can be initialized with WinJS.Utilities.startLog (for logging to the JavaScript console) or assigned to a custom method with logging behaviors defined by the developer. A straight call to the log method without initializing will cause following:

Of course, when the log method is initialized - no errors are reported. However, consider a scenario where settings in the application determine whether the log method will be initialized or not. In that case, what is a safe way to call the log method? Some might create a global variable that could be used in an if statement to see if logging is enabled before every call. That will work, but there is another way. Consider the following code:

The second line of code is “safer” because it starts with a check to see if the log exists. The term “safer” is used instead of “safe” because by saying log “exists” what that really equates to is that it is not one of the following: null, undefined, an empty string, or a numeric value of zero. Even so, it is still safer to use the logical && operator (no if statements needed) because it will exit the statement immediately when a false value is returned.

There is another technique using the|| operator which can help reduce errors by producing a default value if one is not provided. In the following code, the name parameter is given a value if none were already assigned:

To prevent unwanted errors like this, there needs to be a guarantee that the method is safe to call. One way to do so is by using an approach mentioned previously - as seen here:

if (name && name.toUpperCase) {
// safely call name.toUpperCase();
}

At other times it may be more preferable to simply confirm what type it is. A common way to accomplish this is to use the typeof operator which returns a string declaring what the underlying type is as seen here:

The isTypeOf function first checks to see if the t parameter has a value, that the value has a charAt method, and that a call to charAt(0) will not return an empty string. If all conditions are true, the function returns a value based on the comparison of t and the type exposed from Object.prototype.toString.call. Note that if the t parameter is not provided or not a string, an error is thrown using the WinJS.ErrorFromName factory method which is an easy way to create an error object based on name (error type or category) and message.

So why throw an error? Doesn’t that defeat the purpose of preventing problems in the first place? In the above example, the error is thrown from inside a helper function. Because this function could end up in a reusable library, it is a methodology for communicating it is being misused to application level code. With that understanding, you will likely spend far more time handling errors in the application level code vs. throwing them.

The main message up to this point is to take preemptive strikes in your code to minimize errors as much as possible. Now what about the errors that went unhandled?

Leave Nothing Unhandled

For all the unknown errors that could happen in your application, there is a simple way to catch them all in one place. The WinJS.Application object has an onerror event that traps all unhandled errors in one place. Because error could happen at any time, this should be hooked to an event handler as soon as possible in the application lifetime. Most of the JavaScript project templates for the Windows Store contain a default.js file where application initializing occurs. Near the top of that file, you can add an event listener for unhandled application errors like seen here:

If an unhandled error happens anywhere in the application, the above listener function gets called. A message is displayed to the user indicating the details of what has occurred, and then the app stops. The app terminates because the error is still considered unhandled. Returning true from the error handler communicates to the system that the error has been handled and is ok to continue.

Unhandled errors can also be caught at the page level while the page is processing. This is especially easy to do when using WinJS.UI.Pages. The following code is an example of how to add an error event listener for the PageControl instance within the define method:

It is worth repeating that this event only fires if an unhandled error occurs during the initial processing of the page. Therefore, unhandled errors that occur in after the processing of a page (in a click event for example) will be directed up to the application level for inspection.

When Promises are Broken

Promises allow for asynchronous code, and because this introduces it’s own level of complexity, it is important to know how to handle errors when using them. In order to appreciate the different options available, consider the following example of a custom promise:

The doAsync function defined above is a custom promise. When called, it allows a message (provided into the function via the msg parameter) to be used after a number of seconds (determined by the limit parameter) passes by. When the time limit is reached, the “complete” function(represented by c parameter) is called. A “progress” function (represented by p parameter) is called every second, allowing the application to potentially update the UI. And if any errors occur, the catch block passes the error into an “error” function (represented by e parameter). If the value of msg equals “fail”, an error is thrown.

The following code demonstrates all the helper methods that will be used when calling the doAsync function:

Each function calls on WinJS.log to display data. Now here is the code that brings them all together:

doAsync("promise", 4) // doError not called
.then(doComplete, doError, doProgress);
// final call was to doComplete function
doAsync("fail", 4) // doComplete not called
.then(doComplete, doError, doProgress);
// final call was to doError function

In each call to doAsync above, a message is passed in, and the duration of the asynchronous call will be limited to 4 seconds. Each second that ticks by will cause the doProgress function to be called. If all goes well when the 4 seconds are up, the doComplete function is called. However, if the promise encounters an error, the doError function is called instead.

Promises can be chained together to allow one asynchronous call to invoke the next when completed. When chaining promises together, put the error handler only in the final link of the chain – the done method. Here is an example of chaining promises using the doAsync function:

In the promise chain above, when “chain(1)” is complete it calls on “fail”. Since “fail” will cause an error to be thrown, “chain(2)” is never called, and processing is directed to the doError function passed into the donemethod of the chain.

Promises can also be joined together too. This allows multiple asynchronous calls simultaneously, but allowing a method to be called when all the joined promises complete. When handling errors in this scenario, do the following: