Closed chldppwls12 closed 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;
}
}
NestJS에서는 middleware -> guard -> interceptor -> pipe -> controller -> interceptor 순으로 실행
문제 상황
에러를 던지면 ExceptionInterceptor가 잡아서 api 명세에 맞는 형식으로 반환하는 중
하지만 Guard에서 에러 던질 시 (interceptor는 guard 이후 실행되기 때문에)interceptor에서 잡을 수가 없어서 에러가 원하는 형식으로 안 나오는 상황
해결 방안
Guard에서 에러 발생 시에는 try-catch를 사용해 에러 발생 시 직접 원하는 형식으로 변환 필요