Created
July 10, 2019 22:06
-
-
Save GeneralistDev/4e0838b4e897aa0df8dee12f2d6dd6ab to your computer and use it in GitHub Desktop.
Global error handling angularjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (function() { | |
| 'use strict'; | |
| angular.module('app') | |
| .config(['$provide', function($provide) { | |
| $provide.decorator('$http', ['$delegate', '$timeout', '$injector', Decorator]); | |
| function Decorator($delegate, $timeout, $injector) { | |
| function displayAlertModal(message, validationMessages) { | |
| return $timeout(function() { | |
| var $uibModal = $injector.get('$uibModal'); | |
| var AppContext = $injector.get('AppContext'); | |
| $uibModal.open({ | |
| templateUrl: '_shell/GlobalErrorMessage.html', | |
| controller: 'GlobalErrorMessageController', | |
| controllerAs: 'vm', | |
| bindToController: true, | |
| backdrop: 'static', | |
| resolve: { | |
| message: function() { | |
| return message; | |
| }, | |
| organization: function() { | |
| return AppContext.getSettings(); | |
| }, | |
| validationMessages: function() { | |
| return validationMessages; | |
| }, | |
| }, | |
| }); | |
| }, 500); | |
| } | |
| function defaultErrorHandler(err) { | |
| if (!err.status) { | |
| throw err; | |
| } | |
| var alertPromise = null; | |
| if (err.status === 400 && err.data && Array.isArray(err.data) && err.data.length > 0) { | |
| // We have validation messages | |
| alertPromise = displayAlertModal(null, err.data); | |
| } | |
| if (!alertPromise && err.status === 400 || err.status === 500) { | |
| var message = err.data.Message || null; | |
| alertPromise = displayAlertModal(message); | |
| } | |
| err.cancelAlert = function() { | |
| $timeout.cancel(alertPromise); | |
| }; | |
| throw err; | |
| } | |
| var get = $delegate.get; | |
| var post = $delegate.post; | |
| var put = $delegate.put; | |
| var oldDelete = $delegate.delete; | |
| $delegate.post = function() { | |
| return post.apply(this, arguments) | |
| .catch(defaultErrorHandler); | |
| }; | |
| $delegate.put = function() { | |
| return put.apply(this, arguments) | |
| .catch(defaultErrorHandler); | |
| }; | |
| $delegate.oldDelete = function() { | |
| return oldDelete.apply(this, arguments) | |
| .catch(defaultErrorHandler); | |
| }; | |
| $delegate.get = function() { | |
| return get.apply(this, arguments) | |
| .catch(defaultErrorHandler); | |
| }; | |
| return $delegate; | |
| } | |
| }]); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment