When building my website, I have multiple Angular apps that require a global error handler to track and display alerts for errors with codes like 500 and 401. Here is what I have so far:
In order to create a global error handler module, I've set up the following code to inject into my apps:
angular.module('globalErrorHandlerModule', [])
.factory('myHttpInterceptor', ['$rootScope', '$q', function ($rootScope, $q) {
return {
'responseError': function (rejection) {
if(rejection.status == 500){
// show error
}
return $q.reject(rejection);
}
};
}])
.config(function ($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
});
angular.module('myApp', ['globalErrorHandlerModule'])
The challenge I am facing now is figuring out how to actually display the error in an alert. I attempted creating a separate error app and sharing a data factory between them, but the data isn't updating within the app. This is what I tried:
angular.module('globalErrorHandlerModule', [])
.factory('myHttpInterceptor', ['$rootScope', '$q', 'Data', function ($rootScope, $q, Data) {
return {
'responseError': function (rejection) {
if(rejection.status == 500){
// set error
Data.error.message = '500 error';
}
return $q.reject(rejection);
}
};
}])
.factory('Data', function () {
var _error = {
message: "init"
};
return {
error: _error
};
})
.config(function ($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
});
angular.module('globalErrorHandlerApp', ['globalErrorHandlerModule'])
.controller('GlobalErrorCtrl', function ($scope, Data) {
$scope.test = Data.error.message;
});
I then attempted to display the error as follows:
<div ng-controller="GlobalErrorCtrl">
Error {{test}}
</div>
Unfortunately, I only see the initial value and not any updates to the error message. I also tried broadcasting without success. I believe there must be a more effective way to implement this feature, but I haven't discovered it yet. Any guidance or tips would be greatly appreciated. Thank you.