AngularJS $exceptionHandler Service
Last Updated :
23 Jan, 2023
In AngularJS, a service is a function or object that is available for dependency injection (DI) in an AngularJS app. Services are typically used to encapsulate and reuse business logic and other app functionality that is not directly related to the presentation of data in the app.
The $exceptionHandler service is a built-in AngularJS service that can be used to handle exceptions thrown during the execution of an AngularJS app. By default, AngularJS logs uncaught exceptions to the browser's console and displays an error message to the user.
Syntax:
app.factory('$exceptionHandler', function() {
return function(exception, cause) {
// Custom exception handling logic here
};
});
Parameters: The $exceptionHandler service is a function that takes two parameters:
- exception: This is the exception object that was thrown. It contains information about the error, such as the type of error and the error message.
- cause: This is an optional parameter that specifies the cause of the exception. It can be a string or an object that provides more context about the exception.
An exception handler is a service or component that is designed to handle exceptions or errors that may occur in an application. Here are a few examples of what an exception handler service might do:
- Log the exception: An exception handler might log the exception, along with relevant contexts such as the time it occurred, the user that was logged in, and the request that caused the error. This can help developers understand and fix the issue.
- Notify developers: The exception handler might also send an email or other notification to the development team, alerting them to the error and providing them with the details they need to fix it.
- Display an error message to the user: Depending on the nature of the error, the exception handler might display an error message to the user, explaining that an unexpected error occurred, etc.
- Attempt to recover from the error: In some cases, the exception handler might try to recover from the error by attempting to retry the failed operation or by using a fallback solution.
- Terminate the application: If the error is severe and cannot be recovered, the exception handler might terminate the application or shut down certain components to prevent further damage.
Example 1: This example describes a sample error that is made to display on the console using the $exceptionHandler Service.
HTML
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js">
</script>
<style>
h1 {
color: green
}
button {
color: white;
background-color: black;
height: 30px;
width: 160px;
padding: 3px;
margin: 5px;
border-radius: 5px;
}
</style>
</head>
<body ng-app="myApp">
<center>
<h1> Geeksforgeeks</h1>
<div ng-controller="MyCtrl">
<button ng-click="generateError()">
generateError
</button>
</div>
</center>
<script>
angular.module('myApp', [])
.factory('errorService', function ($exceptionHandler) {
return function (message) {
$exceptionHandler(message);
}
})
.controller('MyCtrl', function ($scope, errorService) {
$scope.generateError = function () {
errorService("Error: This is a sample custom Error!");
}
});
</script>
</body>
</html>
Output:
Example 2: In this example, the myCtrl controller has a calculate() function that calculates the square root of a number input by the user. If the user enters a negative number, an exception is thrown with the message "Number must be positive." The exception is caught by the catch block and the error message is displayed in the HTML template using the errorMessage model. The exception is also passed to the $exceptionHandler service, which can be used to log or handle the exception in some other way.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Exception Handling in AngularJS</title>
<style>
input {
width: 100px;
padding: 5px 15px;
margin: 5px 0;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
}
button {
width: 80px;
background-color: #4caf50;
color: white;
padding: 6px 12px;
margin: 5px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
h1 {
color: green;
}
</style>
</head>
<body ng-app="myApp">
<center>
<h1> Geeksforgeeks</h1>
</center>
<div ng-controller="myCtrl">
<p>Enter a number:</p>
<input type="number" ng-model="num" />
<button ng-click="calculate()">Calculate</button>
<p>Result: {{result}}</p>
<p>Any Exception: {{errorMessage}}</p>
</div>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js">
</script>
<script>
angular.module('myApp', [])
.controller('myCtrl', function ($scope, $exceptionHandler) {
$scope.calculate = function () {
try {
if ($scope.num < 0) {
$scope.result = "Not Possible";
throw new Error("Number must be positive.");
}
$scope.result = Math.sqrt($scope.num);
$scope.errorMessage = "No Exceptions";
} catch (e) {
$scope.errorMessage = e.message;
$exceptionHandler(e);
}
}
});
</script>
</body>
</html>
Output:
Reference: https://docs.angularjs.org/api/ng/service/$exceptionHandler
Similar Reads
AngularJS $controller Service AngularJS applications depend on a controller to control the flow of data through an AngularJS application. AngularJS architecture uses the MVC model i.e the Model View Controller. The model is responsible for maintaining the application data, the View for displaying data or some part of data to the
5 min read
AngularJS $location Service The $location in AngularJS basically uses a window.location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in AngularJS. There are various methods in the $location s
4 min read
AngularJS $cacheFactory Service The $cacheFactory service in AngularJS is a factory function that creates new instances of the Cache object, which is a simple in-memory cache that stores key-value pairs. The Cache object is useful for storing data that is expensive to retrieve, such as data that comes from a server or data that is
5 min read
AngularJS $document Service In AngularJS, a service is a function or object that is available for dependency injection (DI) in an AngularJS app. Services are typically used to encapsulate and reuse business logic and other app functionality that is not directly related to the presentation of data in the app. The $document serv
3 min read
Angular.js $log Service The $log service in Angular.js is simply used for logging purposes on the browser console. It is used for the debugging and troubleshooting of the error in the code. It has various implementations like a log, warn, info, error, and debugging, and all the names suggest. It is used for logging, warnin
5 min read
AngularJS $httpParamSerializer Service The AngularJS $httpParamSerializer service is a service that is used to serialize data into a URL-encoded string. It is commonly used with the AngularJS $http service to encode request parameters when making HTTP requests. Syntax: app.controller('myCtrl', function($scope, $http, $httpParamSerializer
4 min read
Servlet - Exception Handling When a servlet throws an exception, the web container looks for a match with the thrown exception type in web.xml configurations that employ the exception-type element. To define the invocation of servlets in response to particular errors or HTTP status codes, you'd have to utilize the error-page el
4 min read
AngularJS $rootElement service The AngularJS $rootElement service is a global service that provides a reference to the root element of the AngularJS application. This can be useful in a variety of scenarios, such as modifying the root element's class name or attributes, or traversing the root element's descendants. Syntax: The sy
3 min read
Angular PrimeNG Message Service Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use the Messages Service in Angular PrimeNG. We will also learn abo
3 min read
Creating an injectable service in Angular In Angular, services are a great way to share data, functionality, and state across different components in your application. Services are typically injected into components and other services as dependencies, making them easily accessible and maintainable. Mostly services are used to create functio
3 min read