본문 바로가기
개발(라이브러리,프레임워크)/Spring boot

Interceptor에서 예외처리 구현

by zieunee 2021. 7. 4.
반응형

exception/패키지 안에 ..

Interceptor은 api요청들어올때 처리해주는 가장 앞단이기 때문에 잘못된 값일때 예외처리를 따로 해주어야한다.

각각 AccessDeniedException / RuntimeException / Exception 로 비교하여 에러 메세지가 떨어지게 만들었다.

RuntimeException.java

@Getter
public class InterceptorException extends RuntimeException {
    private InterceptorExceptionEnum error;

    public InterceptorException(InterceptorExceptionEnum e) {
        super(e.getMessage());
        this.error = e;
    }
}

InterceptorExceptionEntity.java

@Getter
@ToString
public class InterceptorExceptionEntity {
    private String errorCode;
    private String errorMessage;

    @Builder
    public InterceptorExceptionEntity(HttpStatus status, String errorCode, String errorMessage){
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }
}

InterceptorExceptioEnum.java

@Getter
@ToString
public enum InterceptorExceptionEnum {
    // RUNTIME_EXCEPTION(HttpStatus.BAD_REQUEST, "E0001"),
    // ACCESS_DENIED_EXCEPTION(HttpStatus.UNAUTHORIZED, "E0002"),
    // INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "E0003"),
    UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "E0001", "권한이 없습니다."),
    EXPIREDTOKEN(HttpStatus.BAD_REQUEST, "E0002", "만료된 토큰입니다."),
    COUNTERFEIT(HttpStatus.INTERNAL_SERVER_ERROR, "E0003", "위조시도");


    private final HttpStatus status;
    private final String code;
    private String message;

    InterceptorExceptionEnum(HttpStatus status, String code) {
        this.status = status;
        this.code = code;
    }

    InterceptorExceptionEnum(HttpStatus status, String code, String message) {
        this.status = status;
        this.code = code;
        this.message = message;
    }
}

InterceptorExceptionHandler.java

@RestControllerAdvice
public class InterceptorExceptionHandler {

    @ExceptionHandler({RuntimeException.class})
    public ResponseEntity<InterceptorExceptionEntity> exceptionHandler(HttpServletRequest request, final RuntimeException e) {
        e.printStackTrace();
        return ResponseEntity
                .status(InterceptorExceptionEnum.EXPIREDTOKEN.getStatus())
                .body(InterceptorExceptionEntity.builder()
                        .errorCode(InterceptorExceptionEnum.EXPIREDTOKEN.getCode())
                        .errorMessage(e.getMessage())
                        .build());
    }

    @ExceptionHandler({AccessDeniedException.class})
    public ResponseEntity<InterceptorExceptionEntity> exceptionHandler(HttpServletRequest request, final AccessDeniedException e) {
        e.printStackTrace();
        return ResponseEntity
                .status(InterceptorExceptionEnum.UNAUTHORIZED.getStatus())
                .body(InterceptorExceptionEntity.builder()
                        .errorCode(InterceptorExceptionEnum.UNAUTHORIZED.getCode())
                        .errorMessage(e.getMessage())
                        .build());
    }

    @ExceptionHandler({Exception.class})
    public ResponseEntity<InterceptorExceptionEntity> exceptionHandler(HttpServletRequest request, final Exception e) {
        e.printStackTrace();
        return ResponseEntity
                .status(InterceptorExceptionEnum.COUNTERFEIT.getStatus())
                .body(InterceptorExceptionEntity.builder()
                        .errorCode(InterceptorExceptionEnum.COUNTERFEIT.getCode())
                        .errorMessage(e.getMessage())
                        .build());
    }

}

AuthInterceptor.java

여기에서 오류가 나면 throw로 던져준다.

...
if(jwtToken != null){
            try {
                if(jwtUtil.isUsable(jwtToken)) { // JWT 토큰이 유효하면
                    return true;
                }
                throw new InterceptorException(InterceptorExceptionEnum.UNAUTHORIZED);
            } catch (MalformedJwtException e) { // 위조 시도
                log.error("Malformed Jwt Token: {}", e.getMessage());
                throw new InterceptorException(InterceptorExceptionEnum.COUNTERFEIT);

            } catch (ExpiredJwtException e) { // 만료된 토큰
                log.error("ExpiredJ Jwt Token: {}", e.getMessage());
                throw new InterceptorException(InterceptorExceptionEnum.EXPIREDTOKEN);

            }
        } else { // 토큰이 없음

            if(uri.contains("/token")) { // 토큰 발급
                log.info("Generate Token, Request URI: {}", uri);
                return true;
            }
            throw new InterceptorException(InterceptorExceptionEnum.UNAUTHORIZED);
        }
        ...
반응형