STUDY/백엔드

@ControllerAdvice / @RestControllerAdvice

level_? 2021. 2. 3. 16:04

@ControllerAdvice

- Spring에서 제공하는 어노테이션으로 모든 컨트롤러에서 선택한 패키지 또는 특정 어노테이션까지 다양한 컨트롤러에서 적용할 수 있는 전역 코드를 작성할 수 있다. @ExceptionHandler와 함께 사용할 수 있는 예외 처리에 중점을 두고 사용된다.

- JSON으로 처리 결과를 반환하고 싶을 때는 @RestControllerAdvice(@ControllerAdvice + @ResponseBody)를 사용하면 된다.

- AOP(Aspect Oriented Programming) 방식이다. 

- @Controller, @RestController에서 발생한 예외를 @ControllerAdvice 또는 @RestControllerAdvice에서 잡아 처리할 수 있다. 만약 @ControllerAdvice에서 @Controller에서 발생한 예외만 처리하고, @RestControllerAdvice에서 @RestController에서 발생한 예외만 처리하고 싶다면, 

@RestControllerAdvice(annotations = RestController.class)
@ControllerAdvice(annotations = Controller.class)

이렇게 설정해주면 된다.

 

@RestControllerAdvice
public class GlobalExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 여러 예외 처리하고 싶을 때
    //@ExceptionHandler({MethodArgumentNotValidException.class, Excpetion.class}) 
    @ExceptionHandler(MethodArgumentNotValidException.class)    // 예외처리할 exception class 설정
    @ResponseStatus(HttpStatus.BAD_REQUEST)  // HttpStatus 반환값 설정
    protected ErrorResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException                                                                                                                                   exception) {
        logger.error("handleMethodArgumentNotValidException", exception);
        return ErrorResponse.BAD_REQUEST;
    }
}


@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum ErrorResponse {
    BAD_REQUEST("잘못된 요청이거나, 요청구문이 잘못됐습니다."),
    UNAUTHORIZED("요청에 대한 권한이 없습니다."),
    FORBIDDEN("접근이 금지된 요청입니다."),
    NOT_FOUND("요청한 리소스가 존재하지 않습니다."),
    METHOD_NOT_ALLOWED("URL 요청 방식이 올바르지 않습니다."),
    INTERNET_SERVER_ERROR("요청 실행 중 오류가 발생했습니다.");

    private final String message;

    ErrorResponse(final String message) { this.message = message; }
    public String getMessage() { return message; }
}

 

supawer0728.github.io/2019/04/04/spring-error-handling/