我有一个exception.js
脚本,其中包含以下服务:
app.service('Exception', function() {
this.ArgumentUndefinedException = function (message) {
if (!message) {
message = "One or more of the arguments are undefined!";
}
return {
name: 'ArgumentUndefinedException',
message: message
};
}
});
现在我在另一项服务中使用它:
app.service('Joins', ['Exception', function(Exception) {
this.LEFTJOIN = function(leftArray, rightArray, joinOnLeft, joinOnRight, columnFromRightArray) {
if (!leftArray) {
throw new Exception.ArgumentUndefinedException("Left Array is not defined for LEFTJOIN!");
} else if (!rightArray) {
throw new Exception.ArgumentUndefinedException("Right Array is not defined for LEFTJOIN!");
} else if (!joinOnLeft) {
throw new Exception.ArgumentUndefinedException("Join On Left is not defined for LEFTJOIN!");
} else {
// code to do the left join.
}
}
}])
然后,当我在控制器中使用Joins
服务而没有定义所需的参数时,我的自定义异常不会被抛出。我在控制台中看不到任何其他错误消息。它根本没有在表格中显示任何内容。我做错了什么或者是否有更好的方法在Angular中抛出自定义异常?
答案 0 :(得分:4)
以下是您提供的代码的plunker,它完全适合我!
我假设您正在从函数中的控制器调用Joins
服务,以便在出现问题时抛出自定义异常。基于以下内容的是您如何调用服务的代码。
var app = angular.module("app", []);
app.controller('Ctrl', function($scope, $http, Joins) {
$scope.throwException = function() {
Joins.LEFTJOIN(false);
};
});
var app = angular.module("app", []);
app.controller('Ctrl', function($scope, $http, Joins) {
$scope.throwException = function() {
Joins.LEFTJOIN(false);
};
});
app.service('Exception', function() {
this.ArgumentUndefinedException = function(message) {
if (!message) {
message = "One or more of the arguments are undefined!";
}
return {
name: 'ArgumentUndefinedException',
message: message
};
}
});
app.service('Joins', ['Exception', function(Exception) {
this.LEFTJOIN = function(leftArray, rightArray, joinOnLeft, joinOnRight, columnFromRightArray) {
if (!leftArray) {
throw new Exception.ArgumentUndefinedException("Left Array is not defined for LEFTJOIN!");
} else if (!rightArray) {
throw new Exception.ArgumentUndefinedException("Right Array is not defined for LEFTJOIN!");
} else if (!joinOnLeft) {
throw new Exception.ArgumentUndefinedException("Join On Left is not defined for LEFTJOIN!");
} else {
// code to do the left join.
}
}
}]);
<html>
<head>
<script data-require="angularjs@1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
</head>
<body ng-app="app" ng-controller="Ctrl">
<button ng-click="throwException()">Exception</button>
</body>
</html>
<强>更新强>
以下是重构代码的plunker,其中包含有关如何使用服务中的真值条件抛出所有不同错误的注释Joins
$scope.throwException = function() {
Joins.LEFTJOIN(true, false, false); //throw no left array
/* Joins.LEFTJOIN(false, true, false); //throw no right array
Joins.LEFTJOIN(false, false, true); //throw no join on left array
Joins.LEFTJOIN(); //throw default exception
*/
};