In: Categories » Computers and technology » AJAX » Implementing an Error and Exception Handling Strategy
Implementing an Error and Exception Handling Strategy
Problem You want to implement a clean error and exception handling strategy in your applications, to make them run more smoothly. Theory Of course, you might argue that one error is a dialog box and the other is generated in the JavaScript console. The fact that one browser uses a dialog box to show an error and the other does not is a browser issue, not an error issue. A concise way of classifying the two errors is to say that one represents an HTML page initialization error and the other represents an HTML page execution error. When implementing an error strategy, consider the technical implementation. At a technical level, when the first character is processed, the JavaScript runtime is executing and can generate an error. But if an error happens three characters in the processing, you are pretty much powerless to do anything about it. Until the HTML page has been completely processed, you should not enable error handling, because the error handling framework might not be properly initialized.
And if an error does happen at that point, your error handling framework might go off half-cocked. Having an incomplete framework try to process an error will just confuse, not help. Your objective should be to initialize and prepare the error handling framework when the HTML page has been completely processed. To know when to initialize the error handling framework, you need to know when HTML page initialization ends and HTML page runtime begins. Technically, HTML page initialization begins when the first character of the HTML page is processed. And technically, HTML page runtime begins when the window.onload event is called. The window.onload event is called after the HTML page has been processed, including frames and images, and it is the first piece of JavaScript code that when executing can expect the HTML page to be complete. An example implementation of the window.onload event could be as follows:
<html>
<head>
<title>Implementing an Error Handling Strategy</title>
<script language="JavaScript" src="/scripts/jaxson/common.js"></script>
<script language="JavaScript" src="/scripts/jaxson/commontest.js"></script>
<script language="javascript" src="/scripts/jsunit/jsUnitCore.js"></script>
</head>
<script language="javascript">
window.onload = function() {
window.onerror = function( msg, file, location) {
info( "window.onerror", "Msg (" + msg + ") file (" + file +") location (" +➥
location + ")");
}
}
</script>
<body>
In this example, window.onload is near the top of the HTML page, but the function could be put anywhere on the page. In the implementation of window.onload, the window.onerror method is assigned as a global catchall error handler. From a scripting perspective, it is the last point at which you can configure the browser before the browser begins its runtime execution of the HTML page. The window.onerror handler receives three parameters: msg, file, and location. These three parameters represent the message, the file, and the location in the file, respectively.
Within the implementation of the window.onerror handler, the handler could repair and retry, generate a log, or do whatever else is desired. The example window.onerror implementation does not return a true or false value, resulting in the error being propagated to the browser. A false value will propagate and display the error, whereas a true value will not make the browser aware of the error. The example implementation contains a problem, but it’s not with the error handler. The problem is with the assignment of the window.onload function. As the code is written, there is only one function implementation for window.onload, and it initializes the window.onerror function. For an Ajax application of any complexity, it is not possible to assign a single window.onload method, as that would be hogging the method. Solution This solution involves creating a JavaScript delegate, as illustrated by the following source code.
Source: /website/ROOT/ajaxrecipes/javascript/functionsareobjects.html
<html>
<head>
<title>Implementing an Error Handling Strategy</title>
<script language="JavaScript" src="/scripts/jaxson/common.js"></script>
<script language="JavaScript" src="/scripts/jaxson/commontest.js"></script>
<script language="javascript" src="/scripts/jsunit/jsUnitCore.js"></script>
</head>
<script language="javascript">
ops.delegate(window, "onload", function() {
window.onerror = function(msg, file, location) {
info("window.onerror2", "Msg (" + msg + ") file (" + file + ") location (" +➥
location + ")");
}
});
</script>
<body>
In the modified onload implementation, the ops.delegate function is used to create a delegate. For the moment, think of a delegate as a way to have a single method call result in multiple methods being called. (You can find more details about delegates in Recipe 2-17.) The implementation of ops.delegate will test if a function is already is assigned to window.onload. If a function is assigned, then the existing function is converted to a delegate method, and the new function is associated with the delegate.
Then when the browser calls window.onload, it will call both the original function and the new function. In theory, an infinite number of functions can be associated with a delegate. The important thing to remember is that multiple functions can be associated with a single property, which is required for the window.onload method. The following code tests the error handling routine:
var testsToRun = {
throw_exception : function() {
throw new Error("this is an error");
}
};
When the throw_exception function is called, an exception is generated by instantiating the Error object and then throwing it using the throw keyword. In theory, you can throw any object even one that looks like Error. Of course, using Error in this way is the most efficient choice, and this in essence is the basis of your error handling framework. You need something to capture an error, and you need to throw an error. How you capture and process the error is context-specific, so showing you something I or another programmer has implemented in another application is not going to help you here. Another way to capture an error is through an exception handler, as follows:
function Generate() { throw new Error(); }
function CatchAll() {
try {
Generate();
}
catch( e) {
// Do something with error
throw e;
}
}
In this example are two functions: Generate and CatchAll. Generate is used to generate an exception, and CatchAll is used to capture the exception. In JavaScript, you can capture an exception using the try and catch keywords, which catch all errors and exceptions that occur while the code in the try block is executing. When an exception is generated, the code within the catch block is executed. In the example, the error is generated by Generate and caught by the catch block, which then throws the error. When the error is thrown again, the exception will be caught in the window.onload method. The try and catch block is extremely useful, because all errors and exceptions can be caught without the browser being any the wiser. But having a catchall mechanism can make debugging JavaScript more complicated, because errors that occur are processed without having the developer be any the wiser. You might be tempted to use a try and catch block as a general programming technique, but that would be a bad idea.
An error that is thrown is an exception, and an exception is something that should not have happened and is unpredictable. An exception should never happen, whereas an error could happen. The best way to illustrate the difference between and error and an exception is the following example, which shows how an exception can be used to capture an error.
Note This example could have written more succinctly using other keywords, but the point here is to simply show the difference between using a decision to test for an undefined variable and using an exception that executes if the variable happens to be undefined.
var func;
try {
func();
}
catch( e) {
func = Default;
func();
}
The exception example illustrates how an exception handler (try and catch keywords) can be used to catch an exception if the func variable is not assigned to a method. Calling func will generate an exception and trigger the code in the catch block. In the catch block of the exception, the variable func is assigned a default function that works and is called. Using an exception block in this manner is incorrect, because the code as it is written expects that func might not be assigned. If there is an expectation of func not being assigned, then the code should be written to reflect that. A better way to write the same code is as follows:
var func;
if( typeof(func) != "function") {
func = Default;
}
func();
In the rewritten code example, the test of func checks to make sure that func is referencing a function. If func does not reference a function, then func is assigned the default function Default. Then when func is called, no exception will be generated. When you write code, errors and exceptions will be generated, and you will need a strategy to deal with them. Keep the following points in mind when you are developing an error and exception strategy:
• Loading and processing an HTML page involves two phases: HTML page initialization and HTML page execution.
• During HTML page initialization, do not activate your error and exception strategy doing so could have unpredictable results.
• Initialize your error and exception handling strategy in the window.onload method.
• Don’t assume that you are dealing with only one piece of code that needs to be called by the window.onload method. Use a delegate to allow multiple functions to be called.
• Errors and exceptions are not the same thing. Errors can be anticipated and dealt with, but exceptions cannot.
• You can define a global exception handler by implementing the window.error method.
• To handle local exceptions, you can use a try and catch block.
legal notice
Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.
Useful tools and features
related articles
Given the recent interest in Ajax, you’d be forgiven for thinking it was a new technology. In fact, the XMLHttpRequest object has been around for years. In technical terms, asynchronous JavaScript interaction with the server is nothing new. All of the other elements of the Ajax model have also been around for quite some time: CSS, (X)HTML, and DOM Scripting. Yet in 2005, interest in this methodology soared. Could it really be that simply giving this approach a snappy name like Ajax was responsible for the sudde...
2. Understanding the Definition and Philosophy of Ajax
The focus of this article is to provide solutions to some common, general problems and questions that are bound to arise before or during development of Asynchronous JavaScript and XML (Ajax) and Representational State Transfer (REST) applications. These common questions are not always technical in nature, often leaning more toward theory or philosophy of development. The problem with these kinds of questions is that once you begin to think about them, you keep going in a circle and end up where you star...
3. Understanding the Definition and Philosophy of Web Services and SOA
Understanding the Definition and Philosophy of Web Services and SOA Wikipedia offers the following definition of Web services:4 The W3C defines aWeb service as a software system designed to support interoperable machine-to-machine interaction over a network. This definition encompasses many different systems, but in common usage the term refers to those services that use SOAPformatted XML envelopes and have their interfaces described by WSDL. For ex...
4. Understanding the Definition and Philosophy of REST
Understanding the Definition and Philosophy of REST REST is a controversial topic among Web service enthusiasts, because it’s considered to stand for the opposite of what Web services and SOA are trying to achieve. The problem with this thinking is that REST is not in contradiction with the abstract definition of SOA and Web services. REST is in contradiction with technologies such as SOAP, WSDL, and WS-* specifications. The following offers a quick definition of REST:...
5. The Easiest Way to Get Started with Ajax and REST
The Easiest Way to Get Started with Ajax and REST Problem You want to know the best way to get started with writing Ajax and REST. Solution When developing an Ajax and REST application, you must decide on the tools and frameworks you’ll use. The choice is simple: Use whatever you’re using today, and write some Ajax applications. You don’t need to change the tools you’re using today. Whether you’re using ASP.NET, JavaServer Pages (JSP), PHP, Ruby, or Python, you...
6. Testing a Dynamic Contract with Ajax
Coding the Contract Using Test-Driven Development Techniques Coding the contract using agile and test-driven development techniques requires writing a number of tests and implementing aMock URL layer. Problem You want to code the contract using these development techniques. Solution To demonstrate, let’s define a use case, implement the use case as a contract, write a test case(s) to implement the contract, implement the contract in the Mock URL, and finally...
7. Testing the Client Side Logic
Problem You want to effectively test your application’s client-side logic. Theory Testing GUI code tends not to be a productive task because of the complications that arise. The main complication is how to test the correctness of a user interface. Imagine a situation where clicking a button causes a table to be filled with data. Now imagine that when a check box is checked and the button is clicked again, a different table is filled with content. The fact that clicking the same button results in two ...
8. Understanding JavaScript and Types
Understanding JavaScript and Types Problem You want to work around the fact that JavaScript does not have types declared for its variables. Theory JavaScript code does not have any variables with a declared type. The lack of typed variables is apparent when you declare functions. That said, not having typed variable declarations does not mean JavaScript has no types or no type safety. Let’s start out with the simple declaration of a function, as illustrated by the following ex...
