JavaScript for Windows Store Apps: Error Handling
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:
JavaScript runtime error: Object doesn't support property or method 'log'
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:
WinJS.log("Risky", "demo", "info");
WinJS.log && WinJS.log("Safer", "demo", "info");
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:
function echoName(name) {
name = name || "John Doe";
return name.toUpperCase();
}
The above code will produce the following output:
echoName(); // JOHN DOE
echoName("M Palermo"); // M PALERMO
So far so good, but what if the following call is made:
echoName(4);
Passing in a non-string value causes the following error:
JavaScript runtime error: Object doesn't support property or method 'toUpperCase'
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:
var x;
(typeof x === 'undefined') // true
x = 4;
(typeof x === 'number') // true
While typeof performs as expected in most cases, there are other times it may resolve types different than we could, as seen here:
(typeof 'abc' === 'string') // true
(typeof new String("abc") === 'string') // false – type is object
In order to determine the actual type value, consider implementing a helper function like the one demonstrated here:
function isTypeOf(o,t) {
if (t && t.charAt && t.charAt(0)) {
return (Object.prototype.toString.call(o) === "[object " + t + "]");
} else {
throw new WinJS.ErrorFromName("args",
"'t' required and must be a string.");
}
}
isTypeOf("abc", "String"); // true
isTypeOf(new String("abc"), "String"); // true
isTypeOf(4); // error thrown
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:
(function () {
"use strict";
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var nav = WinJS.Navigation;
app.addEventListener("error", function (err) {
var md = Windows.UI.Popups.MessageDialog;
var msg = new md(err.detail.message, "Ooops!");
msg.showAsync();
// return true; // only if error is handled
});
[remaining code...]
})();
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:
WinJS.UI.Pages.define("/pages/errors/errors.html", {
error: function (err) {
WinJS.log && WinJS.log(err.message, "demo", "error");
},
[remaining code...]
});
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:
function doAsync(msg, limit) {
return new WinJS.Promise(
// c complete, e error, p progress
function (c, e, p) {
msg = msg || "no-msg";
limit = limit || 3;
var seconds = 0;
var iId = window.setInterval(function () {
try {
seconds++;
if (msg === "fail") {
throw new WinJS.ErrorFromName(
"promise", "Muhahaha!");
}
p && p(msg + ": " + seconds.toString());
if (seconds > limit) {
window.clearInterval(iId);
c && c(msg);
}
} catch (ex) {
window.clearInterval(iId);
e && e(ex);
}
}, 1000); // repeat every second, stop at limit
});
}
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:
function doComplete(msg) {
WinJS.log && WinJS.log(msg + ": complete", "demo", "info");
}
function doProgress(msg) {
WinJS.log && WinJS.log(msg, "demo", "info");
}
function doError(err) {
var msg = "undefined error";
if (err) {
msg = err.detail;
if (!(msg && msg.message))
msg = err.message || "err type unknown";
}
WinJS.log && WinJS.log(msg, "demo", "error");
}
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:
doAsync("chain(1)", 4)
.then(function (msg) {
doComplete(msg);
return doAsync("fail", 4);
}, null, doProgress)// null passed in for error
.then(function (msg) {
doComplete(msg);
return doAsync("chain(2)");
}, null, doProgress)// null passed in for error
.done(null, doError);
// doError only needed in done method
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 done method 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:
var promises = [];
var i = 0;
// each promise has an error handler
promises[i++] = doAsync("2seconds", 2)
.then(doComplete, doError);
promises[i++] = doAsync("fail", 8)
.then(doComplete, doError);
promises[i++] = doAsync("3seconds", 3)
.then(doComplete, doError);
// join promises
WinJS.Promise.join(promises)
.done(function () {
doProgress("all promises completed");
}, doError);
Unlike chaining, joined promises should have their own error handlers. If a failure happens in one of the promises, it will not stop the others in the join .
On a final note regarding promises, an error handler can be attached to WinJS.Promise.onerror . Do this as a safety net in addition to the methodologies covered so far.
End Gracefully
In summary, remember these useful guidelines and tips while you are writing your Windows Store app with JavaScript:
- Errors happen – even in your code.
- Error messages can be vague, so examine the context of suspicious code!
- Trusting that your code should work is a bad idea.
- Avoid common pitfalls by implementing a good type-checking strategy.
- Handle the unhandled at the application level and page level.
- Use error handlers appropriately when dealing with promises.
If you have not done so already, make sure you are getting all the latest resources by creating a profile at Generation App!!!