메모장

예외처리 좀 더 읽기 작성 하기

gigigugu 2024. 9. 7. 02:01

어플리케이션 코드를 작성하다보면, 다양한 예외처리를 하게 된다.
로그인 로직에서 이메일과 비밀번호를 받아, 이메일로 유저를 조회 할때 아래와 같이 작성할 수 있다.

export class userLoginService {
  constructor( private readonly userRepository: UserRepository ) {}
  async login(email: string, password: string) {
      const user = await this.userRepository.findOneByEmail(email);

    // 유저가 없으면 예외처리
    if(typeof user === 'undefined' || user === null) {
      throw new NotFoundException('유저정보를 찾을 수 없습니다.');
    }

    // 생략...
  }
}

만약 if문의 조건이 복잡하다면, 아래와 같이 Guard static class를 만들어 처리하도록 하는게 좋다고 생각한다.

export class Guard {
  public static isTrue(condition: boolean, error: Error): asserts condition is boolean {
    if (condition) throw error;
  }

  public static isFalse(condition: boolean, error: Error): asserts condition is boolean {
    if (!condition) throw error;
  }

  public static isNonNullable<T>(value: T | null | undefined, error: Error): asserts value is T {
    const isUndefined = typeof value === 'undefined';
    const isNull = value === null;

    if (isUndefined || isNull) throw error;
  }
}

위 Guard class를 적용하거 예외처리를 하면 아래와 같이 처리할 수 있다.

// 이전
if(typeof user === 'undefined' || user === null) {
  throw new NotFoundException('유저정보를 찾을 수 없습니다.');
}

//이후
Guard.isNonNullable(user, new NotFoundException('유저정보를 찾을 수 없습니다.'));