【问题标题】:What should happen when an important constructor argument is missed?当一个重要的构造函数参数丢失时会发生什么?
【发布时间】:2016-05-14 18:22:23
【问题描述】:

我用 es6 创建了一个类,它需要在 options 参数中定义一个属性。

class MyClass{
     constructor(options){
         if(typeof options.name === "undefined")
            console.error("MyClass.constructor: options.name is not defined");
         return this;
     }
}

我可以记录错误,但我不希望此类用户继续。我要返回什么?我还应该返回类的实例吗?

【问题讨论】:

  • 这是否意味着创建此类的每个人都需要将其包装在 try/catch 中?
  • 没有。 JS 异常是未经检查的,就像 java 中的 RuntimeExceptions。
  • 我会退出程序并尝试修复代码,我是认真的 x-)
  • 我的意思是,在这种情况下可能存在设计问题。

标签: javascript


【解决方案1】:

在这种情况下我会抛出一个错误。我会做这样的事情:

class MyClass{
     constructor(options){
         if(typeof options.name === "undefined")
            throw new Error("MyClass.constructor: options.name is not defined");
         return this;
     }
}

您可以阅读有关 throw herehere 的更多信息。 This 是一个类似的 SO Q&A。

【讨论】:

    【解决方案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 的人最不想做的事情就是必须深入其中并找出发生了什么以及如果有办法克服错误。

    【讨论】:

      【解决方案3】:

      如果选项中没有太多属性,我可能会定义一个默认值,这样我就不必抛出错误或阻止代码继续运行。

      class A {
        constructor({ name = 'Andy', age }) {
          console.log(name, age) // Andy, 20
        }
      }
      
      var a = new A({ age: 20 });
      

      【讨论】:

        猜你喜欢
        • 2015-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-17
        • 2012-08-08
        • 2015-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多