【发布时间】: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