Beginning AngularJS

(WallPaper) #1

Chapter 7 ■ ServiCeS and Server CommuniCation


This example assumes that we received a JSON response from the server and that this response was structured
something like {"transactionID": "12587965"}. Of course, in your own projects, you will come across many
different structures and even different formats, such as XML.


Handling Errors

It’s an unfortunate fact of life that things do not always go well. Our applications are going to produce errors for a wide
variety of reasons. Some might be network-related and quite possibly outside of our control. Others might be coding
errors or configuration issues—things well within our control. Regardless of the origin of an error, we should respond
appropriately. A good place to do so is in the promise object’s error method (see Listing 7-13).


Listing 7-13. Handling Errors


promise.error(function (data, status) {


if (status === 0) {
$scope.errorMessage = "network or http level issue";
} else {
$scope.errorMessage = "response HTTP status is " + status;
}
$scope.showErrorMessage = true;
});


This time, we make use of the status parameter. This will tell us how the server responded, by supplying us with
an HTTP status code. Status codes between 200 and 299 are considered successful, so you won’t see any in this range
inside an error callback. If the server didn’t respond at all, due to some kind of network or HTTP-level issue, you will
get 0 as a result.
Listing 7-13 isn’t a very sophisticated way to handle errors from a user perspective, but it is somewhat useful
for “at a glance” debugging purposes. Ideally, though, you would evaluate your particular scenario and determine
whether or not there is any way to recover from, or more gracefully handle, your own errors.


Summary


After looking at some of Angular’s built-in services, we went on to develop our own custom service, learning a little
bit about the $http service in the process. I hope you saw that while creating your own services may mean extra work,
they aren’t terribly difficult to create and are well worth the effort.
While directives get most of the Angular glory, I think that services are in some ways the slightly unsung hero.
In this book, I really only scratched the surface of their possibilities and benefits, but, as you can see, they are a very
capable way of isolating potentially complex logic from your model and view logic, and they are the ideal place for
application-wide logic.

Free download pdf