0

I'm trying to setup solid error handling within my angular web application. I have a lot of various api calls using various sources, within many different controllers and directives. Ideally I'd like to handle resource errors in a manner like this:

$scope.loadData = function () {
    $scope.loaded = false;
    dataFactory.getData($scope.RecordId)
    .$promise
    .then(function (resp) {
        $scope.Data = resp;
        $scope.loaded = true;
    }, function (resp) {
        $scope.loaded = true;
        $scope.handleResourceError(resp);
    })
};

Since I inject $scope in all controllers/directives that would need this functionality, am I able to define a Resource Error method that would be accessible anywhere $scope is injected?

1
  • You would have to put that function in the $rootScope for it to be accessible everywhere. Commented Jul 9, 2015 at 13:30

1 Answer 1

1

Interceptors might help you. instead of writing error handler function every time, you can just bind your function to root scope and call it form the "responseError" interceptor. Here i bind a function to open the error model to $rootScope and i'm calling it form the interceptor. you can find the example below.

Sample code:

(function (global) {
    "use strict";

    angular.module("TestAPp").factory('httpInterceptor', ["$rootScope", "$q", function ($rootScope, $q) {
        return {
        responseError: function (response) {
            /* Open Error model and display error */
            $rootScope.openErrorModel(response);
            /* reject deffered object so that it'll reach error block , else it'll execute success function */
            return $q.reject(response);
        }
        };
    }]);

}(this));

//registering interceprtor

(function (global) {
    "use strict";

    angular.module("TestApp", [])
           .config([ '$httpProvider',function ($httpProvider) {
                /* Register the interceptor */
                $httpProvider.interceptors.push('httpInterceptor');

    }]);

}(this));

PS: My openErrorModel definition

$rootScope.openErrorModel = function (error) {
      $rootScope.errorMessage = error.data;
      $('#errorModal').modal('show');
};

You can refer to Error Handling in angular for more info.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.