ControllerAdvice

By | 2020년 11월 12일
Table of Contents

ControllerAdvice

ControllerAdvice vs RestControllerAdvice

모두 모든 컨트롤러(Controller + RestController) 의 예외를 잡습니다.
차이점은 리턴데이타가 있는가 없는가 뿐입니다.

주의점

ControllerAdvice 가 프로젝트에 여러개인 경우 Spring 은 랜덤한 순서로 ControllerAdvice 를 확인합니다.
ControllerAdvice 의 순서를 고정해 주거나 프로젝트에 하나의 ControllerAdvice 만 두는 것이 좋습니다.

RestControllerAdvice

컨트롤러에서 발생하는 오류를 통합해서 관리할 수 있습니다.

public class DataNotFoundException extends RuntimeException {
    public DataNotFoundException(String message) {
        super(message);
    }
}
@ToString
@Getter
public class ApiResponseMessage implements Serializable {
    private final String code;
    private final String message;

    public ApiResponseMessage(ResponseCode responseCode) {
        this.code = responseCode.getKey();
        this.message = responseCode.getTitle();
    }
}
@Getter
@RequiredArgsConstructor
public enum ResponseCode implements Serializable {

    OK("000", "OK"),
    DATA_NOT_FOUND("404", "데이타가 존재하지 않습니다."),
    UNKNOWN_ERROR("999", "알 수 없는 오류가 발생했습니다.");

    private final String key;
    private final String title;
}
@RequiredArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
public class ExceptionAdvice {

    // 당연한 이야기지만, ControllerAdvice 가 처리하는 Exception 은
    // 컨트롤러에서 발생한 Exception 만이다.
    // Spring Security 와 같이 컨트롤러 상위에서 발생하는 Exception 은 처리하지 않는다.

    @ExceptionHandler(value = {DataNotFoundException.class})
    protected ResponseEntity<?> handleDataNotFoundException(DataNotFoundException e) {
        return new ResponseEntity<>(new ApiResponseMessage(ResponseCode.DATA_NOT_FOUND), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(Exception.class)
    protected ResponseEntity<?> handleException(Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

답글 남기기