$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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book