我创建了一个带有es6的类,需要在options
参数中定义属性。
class MyClass{
constructor(options){
if(typeof options.name === "undefined")
console.error("MyClass.constructor: options.name is not defined");
return this;
}
}
我可以记录错误,但我不希望此类用户继续。我该怎么回事?我还应该返回班级的实例吗?
答案 0 :(得分:4)
在这种情况下我会抛出一个错误。我会做这样的事情:
class MyClass{
constructor(options){
if(typeof options.name === "undefined")
throw new Error("MyClass.constructor: options.name is not defined");
return this;
}
}
答案 1 :(得分:2)
如果您要抛出,则应使用相应的错误类型,以便界面用户可以采取正确的操作。包括文件名和尽可能多的详细信息。您希望尽可能地帮助API用户。
class MyClass{
constructor ( options ) {
if(options === undefined || options === null) {
throw new ReferenceError("MyClass constructor missing required argument `options`.", "filename.js");
} else
if(options.name === undefined) {
throw new ReferenceError("MyClass constructor missing required property `options.name`.", "filename.js");
} else
if( typeof options.name !== "string") {
throw new TypeError("Argument `options.name` should be a string.","filename.js");
} else
if( options.name === "" || options.name.trim() === ""){
throw new RangeError("Argument `options.name` has an invalid value. It requiers one or more alphaNumeric chanracters.","filename.js");
} else
if( options.name.length < 5 ){
console.warning("MyClass constructor. It is recogmended that 'options.name' has more than 5 characters");
}
... all good continue construction
}
}
这样程序员可以选择做什么。它可能需要额外的客户端输入(错误的表单),允许应用程序再次尝试。或者可以将错误传递给可以记录更严重问题的报告界面。我们必须始终提供一切机会来解决问题,并提供尽可能多的信息。没有什么比非描述性的通用错误更糟糕了,有人使用你的API想要做的最后一件事是必须进入它并找出正在发生的事情以及如果有办法如何通过错误。
答案 2 :(得分:1)
如果选项中没有太多属性,我可能会定义一个默认值,所以我不必抛出错误或阻止代码继续。
class A {
constructor({ name = 'Andy', age }) {
console.log(name, age) // Andy, 20
}
}
var a = new A({ age: 20 });