jeudi 30 juillet 2020

Handling errors creting an Entity. Factoy and Result

I write some code to control the way mi entites are created by and static method putting the constructor private. ¿Factory?

I am not returning the instance, but a Resonse With a value Entity if it is isSuccess. The idea is to handle errors whitout thorw and error, just returning an extended response whit that information. [Example all together at the end]

My problem is:

class Customer<CustomerProps> extends Entity<CustomerProps>{
    private constructor(props: CustomerProps){
       
    }

    public static create(props: CustomerProps): Result<Customer>{
        ....
        if(someError) return Result.fail('String error');

        return Result.ok<Customer>(new Entity(props));
    }
}

And the result class

class Result<T>{
  
  private constructor(isSuccess: boolean, error: string, value?: T) {
  ...
  this.isSuccess = isSuccess;
  this.error = error;
  this._value = value;
  }
 
  public getValue(): T{
    if (!this._value) {
        throw new Error("Can't get the value of an error result. Use 'errorValue' instead.")
    }
    return this._value;
  }

  public static ok<U>(value: U): Result<U> {
    return new Result<U>(true, '', value);
  }

  public static fail<U>(error: string): Result<U> {
    return new Result<U>(false, error);
  }

I can now ask if the response was successful and get the value.

The problem is: in Result class I have getValue() and it is asking if there is _value and throwing an error if not. Because in the case of Result.fail() there is no value. Throw Error is the issue... i am doing it again because not always there is _value.

Does this represent a problem for you? Should I just throw an error and Catch that exception?

Aucun commentaire:

Enregistrer un commentaire