<分区>
让我们看一些例子:
我有这个功能:
函数在等待一个参数(index),这样验证好不好?我的观点是,函数不会抛出任何错误,如果参数不是数字,函数将不会被使用,这很糟糕(因为任何正在调试这段代码的人都不会看到这个错误),但我应该到处都使用“try and catch”?
ps:这不是发送到服务器的验证,它只是与用户交互的验证,因此例如,如果用户单击某个按钮以设置某些内容(如颜色),这应该这样做,唯一如果有人通过 javascript 更改其中的值,则会发生此处的错误,但它只会发生在他们的浏览中......
/**
* @param Int index
*/
this.setDrawAttention = function (index) {
if (lodash.isNumber(index) && !lodash.isNaN(index)) {
this.drawAttentionIndex = index;
}
};
或者这个函数会更好(使用 throw,但我不喜欢在任何地方都使用 try catch... 为什么我需要这个?它不会被发送到服务器,并且错误像我之前说过,只有当用户通过 javascript 更改此值时才会发生,但此错误只会显示给他或正在调试它的人,但我不需要这样做...):
/**
* @param Int index
*/
this.setDrawAttention = function (index) {
if (lodash.isNumber(index) && !lodash.isNaN(index)) {
this.drawAttentionIndex = index;
}
else {
throw {...};
}
};
或者很简单,像这样(它不会被发送到服务器,如果有人试图输入其他值,错误将通过浏览器检测到,看看你是否正在调试是很好的......):
/**
* @param Int index
*/
this.setDrawAttention = function (index) {
this.drawAttentionIndex = index;
};