سؤال

Every time I hit the servers using any $resource I want to show the same alert to my users whenever it fails.

Today, it looks like:

function tryAgain() { alert("try again") }
myResource.query().$promise.catch(tryAgain);
myResource.update(...).$promise.catch(tryAgain);
myResource.delete(...).$promise.catch(tryAgain);
otherResource.query().$promise.catch(tryAgain);

Is there a way to configure the default error handling function for ngResource? I'm looking for something like:

$resource.somethingMagicHere.defaults.catch(tryAgain);
هل كانت مفيدة؟

المحلول

You can use an interceptor in your app.config() section. This will catch all response errors originating from $http which $resource uses.

$httpProvider.interceptors.push(function($q) {
  return {
    'responseError': function(response) {
      if (response.status == 401) {
        // Handle 401 error code
      }
      if (response.status == 500) {
        // Handle 500 error code
      }

      // Always reject (or resolve) the deferred you're given
      return $q.reject(response);
    }
  };
});

نصائح أخرى

The @kba answer helped me find the path. The following article made me understand it:

http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

Just declare it once and reuse:

var defaultErrorHandler = function() {
  alert("try again")
}

myResource.query(...).$promise.catch(defaultErrorHandler());            
myResource.update(...).$promise.catch(defaultErrorHandler());
...
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top