Beginning AngularJS

(WallPaper) #1

Chapter 10 ■ Deployment ConsiDerations


One problem here is that we inform the user about the error, but we don’t actually help them to do anything
about it. Another problem is that there is no communication back to us (or our support team) that this error occurred.
We can do a little bit better. As there is little to gain by logging to the browsers console as we do in Listing 10-9, let’s
create a function for logging errors to the server instead.


Listing 10-9. A basic server logging mechanism


function log(sev, msg) {


var img = new Image();
img.src = "log.php?sev=" +
encodeURIComponent(sev) +
"&msg=" + encodeURIComponent(msg);
}


In Listing 10-9, we have a basic function that allows us to capture errors as they occur. This approach works by
making an http GET request for an image on our web server. The image itself won’t be visible within your application;
it exists only as a way to pass the error information from the user’s browser to our applications back-end. Listing 10-10
shows this in action.


Listing 10-10. Using a logging service


var paymentService = null;
try
{
paymentService.payForItem();


}
catch(e){
// alert user to the error
showSomeFriendlyFeedback();
// Trasmit the error to the server
log(1, "001: The user was unable to complete his purchase");
}


There are a few noteworthy things happening in Listing 10-10. We are now using JavaScript’s try/catch error
handling construct; this is a much more elegant and readable approach than the one we took in Listing 10-6. For
dramatic effect, we deliberately create an error within the try block by using the payForItem() method on an object
that is null; this forces program execution into the catch block.
Now that we are within the catch block, we can discuss the two arguments that we provided to our log()
method. The first argument is a severity level; in this case, we set the severity to 1, which is deemed to be the highest
level of urgency. The next argument is a string that represents a description of the error. It is not uncommon to see
error messages with numeric prefixes such as the “001” we use here. These can be quoted to support staff over the
telephone and used to look for problem resolutions more effectively. They can also be used to locate information
programmatically in a knowledge management system, for example.
With the nuts of bolts in place to do the logging, the next thing to consider is what to log and when to log it. Every
application is different, but it goes without saying that anything you consider to be a severity level 1 should almost
certainly be logged. Less severe or purely information logging should perhaps not be done at all. The last thing you
want in very high traffic website is pointless logging requests that will only serve to place more strain on back-end
systems rather than to provide help to developers or end users.

Free download pdf