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.

tip $exceptionHandler does not handle syntax errors.

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.

Note that we have used $http service in the studentController. However, we have not included $http service as a parameter in the controller function to raise an exception for demo purpose. Now, the exception will be handled by $exceptionHandler and displays an alert message.