Tuesday, 1 May 2018

025 AngularJS Exception Handling

AngularJS Exception Handling

         While executing any program , if any unwanted situation is occurred , exception occurs . Most of the programming languages & scripting has facility to handle exceptions. JavaScript use try catch  finally for exception handling purpose.AngularJS $exceptionHandler detective is used to handle exceptions . $exceptionHandler write exception to the browser console , you can override this functionality. The error is written in $log.error by default.

Below is the example of exception handling 


Example
<div>

<!DOCTYPE html>
<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script type="text/javascript">

angular.module("myApp", [])
.controller("myController", function ($scope, $exceptionHandler) 
{
           $scope.myFunction = function ()
          {
               try 
        {
                       throw new Error("Your have generated an exception");
              }
             catch (except) 
       {
                $exceptionHandler(except.message, " : Button was Pressed");
            }
        }
});

</script>
</head>
<body>
           <div ng-app="myApp" ng-controller="myController">
          <button ng-click="myFunction()">
Click Here
</button>
</div>
</body>
</html>
</div>

Output :

















Error handling can be customize also.You can use factory method to create an exception.


Custom Error Handleing


<!DOCTYPE html>
<html>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head runat="server">  

<script>
          var app = angular.module('myApp', []);
         app.factory('$exceptionHandler', function ()
        {

                  return function (exception, cause)
                  {
                         alert( exception.message);
                  }; 
       });


        app.controller('myController', function ($scope) 
    {
              $scope.GenerateErroe = function ()
              {
                       throw { message: 'error occurred' };
              }
      });

</script>
</head>
<body>
                <div ng-app="myApp" ng-controller="myController">
                <input type="button" value="Clik Me!" ng-click="GenerateErroe()" />
</div>
</body>
</html>

Output :


Clik Me!









No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...