Recommended practice for application exception handling in AngularJS

后端 未结 3 773
遥遥无期
遥遥无期 2021-01-31 03:42

I am currently exploring possible methods to handle application-wide exceptions in AngularJS.

One of the things we really wanted to avoid was wrapping multiple parts of

3条回答
  •  生来不讨喜
    2021-01-31 04:06

    whats your opinion to create a centralized error handling function for your app

    so whenever an error happened with your frontend tear (angular, API calls,...) it executed, so no need to write your error handling every time

    so here is my code

    (function () {
        'use strict';
        angular
            .module('app')
            .factory('$exceptionHandler', ExceptionHandler);
    
        ExceptionHandler.$inject = ['$injector']; //for minification 
    
        function ExceptionHandler($injector) {
            var $log, sweetAlert, $translate;
    
            return function exceptionHandler(exception, cause) {
                // Add DI here to prevent circular dependency
                $log = $log || $injector.get('$log');
                sweetAlert = sweetAlert || $injector.get('sweetAlert'); //19degrees.ngSweetAlert2
                $translate = $translate || $injector.get('$translate');
                // $loggerService = $loggerService || $injector.get('$loggerService');
    
                var title, message;
                title = $translate.instant('General error title');
                message = $translate.instant('General error message', { exceptionMessage: exception.message });
                sweetAlert.error(title, message);
    
                $log.error(exception, cause);
                // loggerService.logErrorsToBackend(exception, cause);
            };
        }
    })();
    

    I'm not sure if this approach considered to be a best practice but hope it helps you.

提交回复
热议问题