MrMango
MrMango

Reputation: 33

Error handling in AngularJs

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!

Upvotes: 0

Views: 387

Answers (2)

Jay Regal
Jay Regal

Reputation: 3273

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.

Upvotes: 0

Phil Sandler
Phil Sandler

Reputation: 28016

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

See Interceptor Section of the AngularJs $http documentation.

Upvotes: 2

Related Questions