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 Angular JS modules.
$exception Handler does not handle syntax errors.
AngularJS also includes built-in $exception Handler service, which handles uncaught exceptions in the application.
The default implementation of $exception Handler service logs the exception into the browser console. You can override
this service as per your requirement.
Example
<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>