Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

지석이의 일기

ControllerAdvice을 활용해 전역 CustomException을 설정하자 본문

Java

ControllerAdvice을 활용해 전역 CustomException을 설정하자

91년도에 철산에서 태어난 최지석 2024. 1. 15. 23:55

Interceptor에서 토큰 유효성 체크 도중에 유효하지 않은 데이터를 반환 할때, 에러를 throw해야하는 경우가 있습니다.

그때, @ControllerAdvice를 이용해 Spring Boot에서 전역 예외 처리를 하는 방법에 대해 알아보겠습니다.

 

먼저, 사용자 정의 예외 클래스를 만들어보겠습니다.

@Data
@ToString
public class CustomException extends RuntimeException {

    private String message;
    private String code;
    private String returnUrl;

    public CustomException(String message, String code , String returnUrl) {
        this.code = code;
        this.message = message;
        this.returnUrl = returnUrl;
    }
}

위의 코드에서는 RuntimeException을 상속받아 CustomException을 정의했습니다. 이 예외는 나중에 우리가 원하는 시점에 호출될 것입니다.

그 다음으로, @ControllerAdvice를 이용해 전역 예외 핸들러를 만들어보겠습니다.

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<CustomException> handleCustomException(CustomException e) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e);
    }
}

 

@ControllerAdvice 어노테이션은 모든 @Controller에서 발생할 수 있는 예외를 잡아 처리하는 역할을 합니다. @ExceptionHandler는 특정 예외를 처리하는 메소드를 지정하는데 사용됩니다.

이제, CustomException이 발생하면 handleCustomException 메소드가 실행되어 예외를 처리하게 됩니다. 위의 예에서는 HTTP 상태 코드 401과 함께 에러 메시지를 반환하도록 설정했습니다.

마지막으로, 이 사용자 정의 예외를 실제로 던져보겠습니다.

msg , code , 그리고 전환시킬 url을 반환합니다.

 

 CustomException이 발생하고, GlobalExceptionHandler에 의해 처리되어 401 상태 코드와 "유효성 검사 실패."라는 메시지가 반환됩니다.
이처럼 @ControllerAdvice와 @ExceptionHandler를 활용하면, Spring Boot에서 전역적으로 예외를 처리할 수 있습니다. 이를 통해 코드의 중복을 줄이고, 일관된 예외 처리 방식을 제공할 수 있습니다.