【问题标题】:How to stop a program execution with "throw" in javascript?如何在javascript中使用“throw”停止程序执行?
【发布时间】:2022-07-15 21:54:04
【问题描述】:

我现在正在恢复 javascript 研究,但遇到了一个问题。我有一个 Customer 类,它在构造函数中接收客户数据并在将其分配给其各自的属性之前对其进行验证。当电话号码不正确时,会引发异常,这反过来又必须停止整个程序的执行,然而,这就是问题所在。我抛出异常并用 try/catch 处理它,但程序仍然继续,代码如下:

// Customer class

import { Library } from './Library.js';
import { books } from './books.js';
import chalk from 'chalk';

export class Customer {
    #name;
    #birthdate;
    #email;
    #phone;
    #code;

    constructor(name, birthdate, email, phone) {
        this.#name = name;
        this.#birthdate = birthdate;
        this.#email = email;
        this.#phone = this.#validatePhone(phone);
        this.rented = [];
        this.#code = Math.trunc(Math.random() * 99999); // MUST BE READABLE, ONLY!
    }

    get name() {
        return this.#name;
    }

    get birthdate() {
        return this.#birthdate;
    }

    get email() {
        return this.#email;
    }

    get phone() {
        return this.#phone;
    }

    set name(name) {
        this.#name = name;
    }

    set birthdate(birthdate) {
        this.#birthdate = birthdate;
    }

    set email(email) {
        this.#email = email;
    }

    set phone(phone) {
        this.#phone = phone;
    }

    async rentBoook(title, days) {
        const search = await Library.searchBook(title);
        if(search.length === 0) throw 'This book doesn\'t exist!';

        return await Library.rentBook('O Ar', this, days);
    }

    #validatePhone(phone) {
        try {
            const pattern = /(\(?[0-9]{2}\)?)\s?([0-9]{5})-?([0-9]{4})/;
            if(!pattern.test(phone)) throw 'Invalid phone number!';

            return phone;
        }catch(err) {
            console.log(chalk.red(err));
        }

    }
}
   // Index

    import chalk from 'chalk';
    import { Customer } from './Customer.js';

    const customer = new Customer('John Doe', '20-04-04', 'r@r.com', '(99) 9999-99999');

    customer.rentBoook('O Ar', 7)
    .then(r => console.log(chalk.green('Book rented with success!')))
    .catch(err => console.log(chalk.red(err)));
    // Output

    "Invalid phone number!"
    "Book rented with success!"

【问题讨论】:

  • 由于您正在使用 try/catch 处理该异常,因此您的程序不会崩溃/结束。只有未捕获的异常才会导致程序崩溃。或者你必须在 catch 块中手动退出程序。

标签: javascript oop exception try-catch throw


【解决方案1】:

电话验证应该在 rentBook 方法中处理,因为验证没有在rentBook内部处理并且发生在#phone prop assignment 中(#phone 将变为 undefined),这两种方法相互独立执行。

对于这种情况,当在 Library.search

之前在 rentBook 内完成验证时,将获得预期结果
async rentBoook(title, days) {
       ....
       validatePhone()
       ...
}

删除 validatePhone 方法中的 try catch 并在需要时在rentBook 中使用 try..catch

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    相关资源
    最近更新 更多