0

I am trying to figure out the best way to perform error handling in AngularJs. I am making API calls via $resource and I came up with the following code:

emailService.create($scope.emailTemplate).$promise.then(function(data) {
    if (data.success) {
        $rootScope.showSuccess("Template created.");
        $scope.reset();
    }
}, function (error) {
    if (error.data != null) {
        $rootScope.showError(error.data);
    } else {
        $rootScope.showError();
    }
});

$rootScope.showError() and .showSuccess are just basic functions that display a message in a div.

Is there anyway to intercept $resource errors and perform the logic above without having to liter my controller with this code in every call I make?

Thank you!

1
  • 1
    Just a comment unrelated to the question: instead of storing a function on $rootScope you should create a service and store it in there. Commented Jun 11, 2014 at 13:43

2 Answers 2

2

You can create a global error handler using an http interceptor.

See Interceptor Section of the AngularJs $http documentation.

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

Comments

0

To catch all $resource errors, use an HTTP Interceptor, as suggested in this answer.

If you require fine-grained control over your error-handling, in the supplied example, you could move your error-handling logic into a separate function. This allows you to re-use it.

Example:

 emailService.create($scope.emailTemplate).$promise.then(function(data) {
    if (data.success) {
        $rootScope.showSuccess("Template created.");
        $scope.reset();
    }
})
.catch(errorCatcher);

function errorCatcher(error) {
    if (error.data != null) {
        $rootScope.showError(error.data);
    } else {
        $rootScope.showError();
    }
};

Should you want to re-use this in other controllers, you could create an error-handling service that provides this function.

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.