본문 바로가기
프로젝트

GiftFunding) 예외 처리하기 (@ExceptionHandler, @RestControllerAdvice)

by son_i 2023. 11. 21.
728x90

각 에러들을 의도한 errorCode, Message 형태로 보여주기 위해 ErrorResponse dto생성.

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ErrorResponse {
    private ErrorCode errorCode;
    private String errorMessage;
}


Controller에서 Return할 때 발생하는 에러를 처리하기 위해 GlobalHandler생성

GlobalExceptionHandler

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(UserException.class)
    public ErrorResponse handleUseException(UserException e) {
        log.error("{} is occurred", e.getErrorCode());

        return new ErrorResponse(e.getErrorCode(), e.getErrorMessage());
    }
}

 

- @RestControllerAdvice

  : @ExceptionHandler, @ModelAttribute, @InitBinder가 적용된 메서드들에 aop를 적용해 Controller 단에 적용하기 위해 고안된 어노테이션. 클래스에 선언해서 모든 컨트롤러에 대해 전역적으로 발생할 수 있는 예외를 잡아서 처리

 

- @ExceptionHandler

  : @Cotroller로 선언된 클래스 안에서 이 어노테이션으로 메소드 안에서 발생할 수 있는 예외를 처리할 수 있다.

  : value 값으로 어떤 Exception을 처리할 것인지를 넘겨주면 특정 Exception 이 발생했을 때 실행될 메소드를 만들 수 있다.

 

-> @RestControllerAdvice에서 @ExceptionHandler를 사용해서 발생하는 에러들을 모두 잡아줄 수 있도록 한다.

 

@ControllerAdvice는 @Component 어노테이션을 가지고 있어 컴포넌트 스캔을 통해 스프링 빈으로 등록된다.

@RestControllerAdvice는 @ControllerAdvice와 @ResponseBody 어노테이션으로 이루어져있고 Response Body로 값을 리턴할 수 있다.

 

-> GlobalExceptionHandler 클래스에서 커스텀에러를 상단에, 자주 발갱하는 에러를 중간에 , 하단에 Exception을 처리해주면 모든 예외에 대한 처리를 할 수 있다.

 

-> ErrorCode enum 클래스를 만들어서 에러메세지들을 관리해주면 좋다.

@Getter
@AllArgsConstructor
public enum ErrorCode {
    USER_DUPLICATED("중복된 이메일입니다.");

    private final String description;
}

 

 

->RuntimeException을 상속받는 CustomException을 만들어 발생할 에러코드와 에러 메세지를 필드로 선언한다.

@Getter
public class UserException extends RuntimeException{
    private final ErrorCode errorCode;
    private final String errorMessage;

    public UserException(ErrorCode errorCode) {
        this.errorCode = errorCode;
        this.errorMessage = errorCode.getDescription();
    }
}