Chapter 19, $exceptionHandler (Pro AngularJS)

by js_test

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<body ng-app="exampleApp" ng-controller="defaultCtrl">
    <div class="panel panel-default">
        <div class="panel-body">
            <button class="btn btn-primary" ng-click="throwEx()">Throw Exception</button>
        </div>
    </div>
</body>

JavaScript

var exampleApp = angular.module("exampleApp", []);

exampleApp.controller("defaultCtrl", function ($scope, $exceptionHandler) {
    $scope.throwEx = function () {
        try {
            throw new Error("Triggered Exception");
        } catch (ex) {
            $exceptionHandler(ex.message, "Button Click");
        }
    }
})

exampleApp.factory("$exceptionHandler", function ($log) {
    return function (exception, cause) {
        $log.error("Message: " + exception.message + " (Cause: " + cause + ")");
    }
});