Since I read a few articles on error handling, i still wondering wether throw exception on a validation logic in the value object is the bad way. For instance, I have this class below which is the value object:
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;
}
}
So,What if there best way to to handling error instead of throw error like i did. Thanks :)