chldppwls12 / travel-diary-server

✏️ 나만의 여행 기록장, Traily Server
0 stars 0 forks source link

NestJS 요청 처리 순서 관련 이슈 #2

Closed chldppwls12 closed 1 year ago

chldppwls12 commented 1 year ago

NestJS에서는 middleware -> guard -> interceptor -> pipe -> controller -> interceptor 순으로 실행

문제 상황

에러를 던지면 ExceptionInterceptor가 잡아서 api 명세에 맞는 형식으로 반환하는 중

@Injectable()
export class ExceptionInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      catchError((err) => {
        const response = context.switchToHttp().getResponse();
        response.status(err.status).json({
          status: err.status,
          message: err.message,
        });
        return throwError(err);
      }),
    );
  }
}

하지만 Guard에서 에러 던질 시 (interceptor는 guard 이후 실행되기 때문에)interceptor에서 잡을 수가 없어서 에러가 원하는 형식으로 안 나오는 상황

해결 방안

Guard에서 에러 발생 시에는 try-catch를 사용해 에러 발생 시 직접 원하는 형식으로 변환 필요

chldppwls12 commented 1 year ago

LocalStrategy의 validate 내부에 try-catch 사용해서 해결

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
      usernameField: 'email',
    });
  }

  async validate(email: string, password: string): Promise<boolean> {
    try {
      await this.authService.validateUser(email, password);
    } catch (err: any) {
      throw new HttpException(
        {
          status: err.getStatus(),
          message: err.message,
        },
        err.getStatus(),
      );
    }
    return true;
  }
}