$exceptionHandler

AngularJs Exception/Error Handling using $exceptionHandler

Hello everyone, I am going to share the AngularJs exception or error handling using  $exceptionHandlerThe AngularJs $exceptionHandler  is use to catch and handle the exceptions or errors. The details as given below.


The HTML Code-Sample

<div ng-app="exceptionApp" ng-controller="ExceptionCtrl"></div>

The AngularJs Code-Sample

var app = angular.module('exceptionApp', []);
app.provider({
    $exceptionHandler: function () {
        var errorHandler = function (ex) {
            alert(ex);
            //console.log(ex);
        };

        this.$get = function () {
            return errorHandler;
        };
    }
});

app.controller('ExceptionCtrl', ["$scope", "$exceptionHandler",
 function ($scope, $exceptionHandler) {
    $scope.name = "Anil Singh";

    //Throw error here using handler as function.
    $exceptionHandler.handler('Throw error');
}]);

The Live demo (HTML + AngularJs) code-sample

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>$exceptionHandler in AngularJs</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
    <script src="https://code.angularjs.org/1.4.7/angular-messages.js"></script>
    <script>
        var app = angular.module('exceptionApp', []);

        app.provider({
            $exceptionHandler: function () {
                var errorHandler = function (ex) {
                    alert(ex);
                    //console.log(ex);
                };

                this.$get = function () {
                    return errorHandler;
                };
            }
        });

        app.controller('ExceptionCtrl', ["$scope", "$exceptionHandler", function ($scope, $exceptionHandler) {
            $scope.name = "Anil Singh";

            //Throw error here using handler as function.
            $exceptionHandler.handler('Throw error');
        }]);
    </script>
</head>
<body ng-app="exceptionApp" ng-controller="ExceptionCtrl">
    <h1>Use of $exceptionHandler in AngularJs</h1>
    <p>Hello {{name}}!</p>
</body>
</html>


The output: go to link http://embed.plnkr.co/x6bqJg/preview

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^