New version Angular 9

AngularJS Tutorial - 5 - Error handling

In this part we will discover services and factories with wich we will manage the error handling.

Screenshot

Download

The source for this part is here: 05_errorservices.zip.

The samples can be run with Firefox, in general or by running, into the directory,

Services and factories

In angular is possible to define

Factory

For example a factory can be the following. The "Setup DateFactory" is colled only once, hence the setup is executed only once.

module.factory('DateFactory',[ function() {
    console.log("Setup DateFactory");
    return function(prefix){
        var date = new Date();
        return prefix+date;
    }
}]);

When i include it as dependency in a controller i can invoke the function returned.

customers.controller('CustomersController',['DateFactory',function(DateFactory){
    $scope.currentDate = DateFactory("prefix");
}]);

Service

An object is created, once, with the specific methods and variables exposed. The "Setup DateService" is called only once, hence the setup is executed only once.

module.service('DateService',[ function() {
    console.log("Setup DateService");
    this.prefixDate = function(prefix){
        var date = new Date();
        return prefix+date;
    }
}]);

When i include it as dependency in a controller i can invoke the function exposed by the object.

customers.controller('CustomersController',['DateService',function(DateService){
    $scope.currentDate = DateService.prefixDate("prefix");
}]);

Making a service with a factory

I can also create the data service with a factory

module.factory('DateServiceFactory',[ function() {
    console.log("Setup DateServiceFactory");
    this.dateService = {
        prefixDate: function(prefix){
            var date = new Date();
            return prefix+date;
        }
    }
    return this.dateService;
}]);

And i will use it in the controller like the following. With this approach i have still a singleton service.

customers.controller('CustomersController',['DateServiceFactory',function(DateServiceFactory){
    $scope.currentDate = DateServiceFactory().prefixDate("prefix");
}]);

Error Messages

We will creat a new module in its directory (app/common/module.js) with an additional services.js file. We will add this module as dependency for the customers module.

We will create a service to manage the messages in services.js. Note the usage of the $rootScope. This is to ensure that ALL application manage the messages consistently.

common.service('globalMessagesService', ['$rootScope',function($rootScope) {
    
    $rootScope.messages = [];
    
    this.showMessage = function(text,level){
        $rootScope.messages.push({
            text:text,
            level:level
        });
    }
    
    this.clearMessages = function(){
        $rootScope.messages = [];
    }
}]);

On the main page we will add the bindings for the messages. Note that we found now that the rootscope is the one visible right after the declaration of the ng-app!

<body ng-app="app">
    <div class="alert alert-danger"
         role="alert" data-ng-repeat="message in messages">
        <p>{{message.text}}</p>
    </div>
    <div ng-view></div>
</body>

Handling errors

To add error handling on the controllers we will add to them a dependency form globalMessagesService.

On their constructor we will add the cleanup of errors. The same function will be called as first line in update,delete and save methods.

    globalMessagesService.clearMessages();

Then after all calls to $http.succes(...) we will add the error management:

            succes(....).
            error(function(data,status,headers,config){
                globalMessagesService.showMessage("Error "+status,"error");
            })

Now going on a non existing customer detail we will see the error :)


Last modified on: April 10, 2015