简体   繁体   中英

Handling Errors best pratices in Typescript

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 :)

One of the benefits of using value objects is that they can enforce their own invariants. It's a good idea to follow the "always valid" principle meaning that entities, aggregate roots and value objects are never in a state that violates their invariants.

As such, there is no problem in throwing exceptions from the value object. In fact, in your example it should be stricter. You can currently create a Username Value Object that would fail the isValidName() test as it is not checked prior to completion of construction.

I'd refactor to this:

export class UserName {
  private readonly value: string;

  constructor(value: string) {
    trimmed: string;
    trimmed = value.trim();
    
    if (trimmed === "") {
       throw new UserNameError("Username is required!.");
    }

    if (!/^[a-zA-Z]+$/.test(trimmed)) {
      throw new UserNameError("user name should contain only letter");
    }    

    this.value = trimmed;
  }

  static userNameOf(name: string): UserName {
    return new UserName(name);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM