Exception Handling in AngularJS - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
Exception Handling in AngularJS

Exception Handling in AngularJS

Exception Handling in AngularJS

Every application needs proper exception handling mechanism. You can use try, catch, and finally block of JavaScript to handle exceptions in AngularJS modules.
AngularJS also includes built-in $exceptionHandler service, which handles uncaught exceptions in the application
The default implementation of $exceptionHandler service logs the exception into the browser console. You can override this service as per your requirement.
The following example demonstrates uncaught exception handling using $exceptionHandler service.
Example: $exceptionHandler
<!DOCTYPE html>
<html ng-app="studentApp">
<head>
    <script src="~/Scripts/angular.js"></script>
</head>
<body class="container" ng-controller="studentController">
    Status: {{status}} <br />
    Data: {{data}} <br />
        <input type="button" value="Get Data" ng-click="getStudent()" />
    <script>
        var app = angular.module('studentApp', []);
        
        app.config(function ($provide) {

            $provide.decorator('$exceptionHandler', function ($delegate) {

                return function (exception, cause) {
                    $delegate(exception, cause);

                    alert('Error occurred! Please contact admin.');
                };
            });
        });

        app.controller("studentController", function ($scope) {

            var onSuccess = function (response) {
                $scope.status = response.status;
                $scope.data = response.data;

            };

            var onError = function (response) {
                $scope.status = response.status;
                $scope.data = response.data;

            }
            $scope.getStudent = function () {
                $http.get("/getdata").then(onSuccess, onError);

            };
        });

    </script>
</body>
</html>
In the above example, we override the $provide service's default behavior using $provide.decorate() method in the app.config() method. The decorate method allow us to override or modify the behavior of the service. So, in the decorate method, we display custom error messages along with logging exception messages to the browser console.

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.