Skip to content

Instantly share code, notes, and snippets.

@haraldfianbakken
Last active August 29, 2015 14:00
Show Gist options
  • Save haraldfianbakken/11177937 to your computer and use it in GitHub Desktop.
Save haraldfianbakken/11177937 to your computer and use it in GitHub Desktop.
Global error handling in angular
angular.module('MyApp').config(function($httpProvider){
$httpProvider.interceptors.push(function($rootScope, $q){
return {
'request': function(config){
config.timeout = 5000;
return config;
}
}
});
$httpProvider.responseInterceptors.push(function($timeout, $q) {
var fullHeight = $(this).height();
var elementsList = $("#root");
var showMessage = function(content, classname, time) {
elementsList.children().hide().delay(time).fadeIn('fast');
$('<div/>')
.addClass(classname)
.hide()
.fadeIn('fast')
.delay(time)
.fadeOut('fast', function() { $(this).remove(); })
.appendTo(elementsList.parent())
.text(content)
.height(fullHeight)
};
return function(promise) {
return promise.then(function(successResponse) {
return successResponse;
}, function(errorResponse) {
switch (errorResponse.status) {
case 0:
showMessage('Operation timed out!', 'errorMessage', 10000);
break;
case 401:
showMessage('You are not logged in!', 'errorMessage', 10000);
break;
case 403:
showMessage('Insufficient privileges for this operation', 'errorMessage', 10000);
break;
case 500:
showMessage('Internal server error' + errorResponse.data, 'errorMessage', 10000);
break;
default:
showMessage('Oops - some other error occured' + errorResponse.status + ': ' + errorResponse.data, 'errorMessage', 10000);
}
return $q.reject(errorResponse);
});
};
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment