【发布时间】:2021-10-15 21:53:49
【问题描述】:
自从我阅读了几篇有关错误处理的文章后,我仍然想知道在值对象中的验证逻辑上抛出异常是否是不好的方法。例如,我在下面有这个类,它是值对象:
export class UserName {
private readonly value: string;
constructor(value: string) {
this.value = this.evaluateName(value);
}
private evaluateName(value: string): string {
value = value.trim();
if (value === "") {
throw new UserNameError("username is required!");
}
return value;
}
static userNameOf(name: string): UserName {
return new UserName(name);
}
public isValidName(): boolean {
if (!/^[a-zA-Z]+$/.test(this.value)) {
throw new UserNameError("user name should contain only letter");
}
return true;
}
}
那么,如果有最好的方法来处理错误而不是像我一样抛出错误。 谢谢:)
【问题讨论】:
标签: typescript error-handling domain-driven-design value-objects