我有一个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中引发自定义异常?
这是您提供的代码的一个有用的插件,它非常适合我!
我假设您是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="[email protected]" 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>
更新
这是重构代码的小插曲,其中包含有关如何在服务中使用真值条件引发所有不同错误的注释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
*/
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句