Open In App

AngularJS $exceptionHandler Service

Last Updated : 23 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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=
    </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=
    </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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads