Jwt 에러 바인딩을 해보자

김건우·2024년 6월 27일

개발 이야기

목록 보기
5/14

401...401...401...

항상 토큰을 넣으면 클라이언트에게 반환되는 에러는 401 인증 안됨 이었다. 이게 토큰 타입 문제인지, 만료가 된건지 아니면 토큰이 잘못된 건지 알 방도가 없었다.

그래서 이번 기회에 토큰 에러를 직접 커스텀하고 추가하여 제대로 된 에러 바인딩을 하고자 했다.

기존 코드

public Jws<Claims> getClaims(final String token) {
        try {
            return Jwts.parser().setSigningKey(jwtProperties.getSecretKey()).parseClaimsJws(token);
        } catch (ExpiredJwtException e) {
            throw new IllegalArgumentException("만료된 토큰");
        } catch (UnsupportedJwtException e) {
            throw new IllegalArgumentException("지원되지 않는 토큰");
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("잘못된 토큰");
        }
 }

기존에 있던 에러 처리는 IllegalArgumentException으로 일괄 처리가 되어 있어서 알아보기가 힘들었다.

그래서 먼저 error 처리와 excetion 클래스를 통해 각각의 예외를 처리해 주었다.

@Getter
@RequiredArgsConstructor
public enum JwtTokenError implements ErrorProperty {

    JWT_TOKEN_ERROR(HttpStatus.BAD_REQUEST, "잘못된 타입"),
    JWT_EXPIRED(HttpStatus.GONE,"만료된 토큰"),
    JWT_ERROR(HttpStatus.BAD_REQUEST,"잘못된 토큰"),
    JWT_NOT_SUPPORT(HttpStatus.BAD_REQUEST,"지원하지 않는 토큰");

    private final HttpStatus status;
    private final String message;

}

이런 식으로 에러를 커스텀 해 주었다.

최종적으로 변경된 코드는 아래와 같다.

public Jws<Claims> getClaims(final String token) {
        try {
            return Jwts.parser().setSigningKey(jwtProperties.getSecretKey()).parseClaimsJws(token);
        } catch (ExpiredJwtException e) {
            throw TokenExpiredException.EXCEPTION;
        } catch (UnsupportedJwtException e) {
            throw TokenNotSupportException.EXCEPTION;
        } catch (IllegalArgumentException e) {
            throw TokenErrorException.EXCEPTION;
        }
}

이런 식으로 에러를 커스텀하여서 클라이언트에서 무슨 에러인지 바로 알 수 있도록 하였다.

profile
백엔드 개발자, 김건우입니다.

0개의 댓글