Skip to content

Instantly share code, notes, and snippets.

@gruppjo
Last active August 29, 2015 14:09
Show Gist options
  • Save gruppjo/81e4b2c092e49b55edec to your computer and use it in GitHub Desktop.
Save gruppjo/81e4b2c092e49b55edec to your computer and use it in GitHub Desktop.
angular seamless error-handling
// new version with service and $injector.get('nameOfService'); ??
// ERROR-HANDLING
.config(function ($provide, $httpProvider) {
// error-interceptor
$provide.factory('errorHandlerInterceptor', function ($q, $rootScope) {
return {
response: function (response) {
// only handle remote XHR requests
if (response.config.url.search(/\/\//) !== -1) {
// handle custom error codes from backend maybe?
}
return response;
},
responseError: function (rejection) {
// use broadcast and not service, since service can't depend on $http (circular dep)
$rootScope.$broadcast('httpError', rejection);
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('errorHandlerInterceptor');
})
// MESSAGING
.run(function ($rootScope, $timeout, $window) {
var tolerance = 3000;
var offset = 150;
var errors = {};
var getKey = function (rejection) {
// build key based on url and http status
return rejection.config.url + ':' + rejection.status;
};
var addError = function (rejection) {
errors[getKey(rejection)] = rejection;
};
var deleteError = function (rejection) {
delete errors[getKey(rejection)];
};
$rootScope.$on('httpError', function (event, rejection) {
var errorKey = getKey(rejection);
// don't treat same error several times within tolerance
if (!errors[errorKey]) {
addError(rejection);
// wait a little to ensure no further change of message/cancellation
$timeout(function () {
if (errors[errorKey]) {
// TODO: display error
$window.alert(rejection.status);
}
}, offset);
// delete error after tolerance
$timeout(function () {
deleteError(rejection);
}, tolerance);
}
});
$rootScope.$on('httpErrorCancel', function (event, rejection) {
deleteError(rejection);
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment