HTML and CSS Reference
In-Depth Information
Detecting Errors
The first step in implementing an error handling strategy is detecting the fact that errors have
occurred. The first type of error can be handled by the try/catch block within functions, or
via registered callbacks on asynchronous APIs. All APIs that utilize asynchronous callbacks
differentiate between success and failure scenarios, and we have also seen jQuery promises
provide direct support for this.
The second type of exception can be handled with try/catch blocks, but in general should
not be. By definition, these errors should not occur, therefore you should prevent them from
occurring rather than handling them.
For instance, consider a scenario where we have been passed an object that may be un-
defined, and we wish to access a property on it. We could write this as follows:
function accept(obj) {
try {
console.log(obj.property1);
} catch (e){}
}
It is far better to write this as follows:
function accept(obj) {
if (obj) {
console.log(obj.property1);
}
}
It is still important to know that unexpected errors have occurred, otherwise you will have
no way of knowing the code contains a bug. Rather than adding try/catch blocks to all our
functions, a more effective strategy for learning than an unanticipated error has occurred is
by adding an onerror listener to the window :
window.onerror=function(message, url, lineNumber) {
console.log('Message:'+message);
console.log('URL:'+url);
console.log('Line:'+lineNumber);
}
Add the following to the tasks.html page.
Now, we will add the following buggy function to the public section of tasks-controller.js:
Search WWH ::




Custom Search