Javascript es6类处理错误

标签 javascript class error-handling

我创建了一个 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 个完全无效的参数调用 new Service(例如,undefined 重复 13 次)。

所以我可能会使用一个选项对象(因为它对调用者来说更容易)结合参数解构,然后单独验证,例如:

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...*/});

关于Javascript es6类处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43557415/

相关文章:

javascript - 如何在 2 个选择元素中交换所选选项?

javascript - 最小的音频文件 : MP3, Ogg 还是 Wav?

python - 在 python 2.7 中创建类的实例

c++ - 如何根据初始化参数修复类函数行为

javascript - 如何使用AJAX上传和预览上传的图片

JavaScript 生成 2 个数字之间的所有数字

javascript - 按类添加事件监听器,在 JS 中将 ID 作为参数传递

bash - Shell脚本命令(例如 “make”)中的错误检测

ios - 捕获所有 "unexpectedly found nil while unwrapping an Optional value"

Android setError ("error") 在 Textview 中不起作用