簡體   English   中英

Javascript ES6類處理錯誤

[英]Javascript es6 class handling error

我創建了一個JS類。 這是下面的代碼:

export default class Service {
    constructor(
        serviceId,
        serviceName,
        serviceDescription,
        serviceImageName,
        categoryId,
        servicePrice,
        currencyCode,
        acceptPayment,
        serviceDuration,
        multipleBookingPerSlot,
        mode,
        tzSupport,
        minOptionCount
    ) {
        try{
            this.id = serviceId;
            this.title = serviceName;
            this.subTitle = serviceDescription;
            this.imageUrl = serviceImageName;
            this.categoryId = categoryId;
            this.price = servicePrice;
            this.currencyCode = currencyCode;
            this.acceptPayment = acceptPayment;
            this.meetingDuration = serviceDuration;
            this.multipleBookingPerSlot = multipleBookingPerSlot;
            this.serviceName = serviceName;
            this.mode = mode;
            this.tzSupport = tzSupport;
            this.session = minOptionCount
        } catch(e){
            if(e instanceof ReferenceError){
                console.error("Service data missing.")
            }
        }

    }
}

我的目標是,如果Service新對象創建時像new Service('1')如果缺少任何鍵,應該拋出錯誤並停止執行。 我怎樣才能做到這一點?

如果調用者沒有提供足夠的參數,則不會收到ReferenceError ,您只會在參數中看到undefined

您有13個參數(實在太多了)。 您可以做蠻力的事情:

if (arguments.length < 13) {
    throw new Error("Missing arguments");
}

但是,我建議改為使用構建器模式或選項對象,而不要使用13個離散參數。 超過三個參數很難管理。

例如,帶有選項對象:

export default class Service {
    constructor(
        options
    ) {
        ["id", "title", "subTitle", "imageUrl", "categoryId", "price", "currencyCode",
        "acceptPayment", "meetingDuration", "multipleBookingPerSlot", "serviceName",
        "mode", "tzSupport", "session"].forEach(name => {
            if (!options.hasOwnProperty(name)) {
                throw new Error(name + " is a required option");
            }
        });
        Object.assign(this, options);
    }
}

用法:

let s = new Service({id: 1, title: "foo", /*...etc...*/});

這樣,調用者就不會迷失在眾多的參數中。


但是 ,如果驗證參數值是否存在很重要,驗證參數值是否也很重要? 沒有什么可以阻止我使用13個完全無效的參數(例如, undefined重復13次)來調用new Service

因此,我可能會使用一個options對象(因為對調用者而言它要容易得多)與參數解構然后進行單獨驗證相結合,例如:

export default class Service {
    constructor({                 // <== Notice the {
        id,
        name,
        decription,
        imageUrl,
        categoryId,
        price,
        currencyCode,
        acceptPayment,
        meetingDuration,
        multipleBookingPerSlot,
        mode,
        tzSupport,
        minOptionCount
    }) {                          // <== And the }
        this.id = validate.positiveNumber(id);
        this.title = validate.nonBlank(name);
        this.subTitle = validate.nonBlank(description);
        this.imageUrl = validate.URL(imageUrl);
        this.categoryId = validate.positiveNumber(categoryId);
        this.price = validate.price(price);
        this.currencyCode = validate.currencyCode(currencyCode);
        this.acceptPayment = validate.boolean(acceptPayment);
        this.meetingDuration = validate.duration(meetingDuration);
        this.multipleBookingPerSlot = validate.boolean(multipleBookingPerSlot);
        this.serviceName = this.title; // Already validated
        this.mode = validate.mode(mode);
        this.tzSupport = validate.tzSupport(tzSupport);
        this.session = validate.whateverThisIs(minOptionCount);
    }
}

... validate是一組可重復使用的驗證。 用法與上面相同:

let s = new Service({id: 1, title: "foo", /*...etc...*/});

正如我已經評論過的,將undefined分配給objects屬性是完全有效的。 解決方案可能是針對undefined檢查參數Arraylike的值:

constructor(a,b,c){
   if(arguments.length!=3){//check length
     return;
   }
   for(var a=0;a<arguments.length;a++){
      if(arguments[a]===undefined){//check against undefined
          return;
       }
    }
  //your code
}

http://jsbin.com/vugepakama/edit?console

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM