[내배캠/TIL(7/20)]Spring 사용자 정의 예외 처리

손홍서·2022년 7월 20일
0

Spring

목록 보기
23/24

day62 TIL

Custom Exception 만들기

  • 사용자 정의 예외 클래스는 컴파일러가 체크하는 일반 예외로 선언할 수도 있고, 컴파일러가 체크하지 않는 실행 예외로 선언할 수도 있다.
  • 일반 예외로 선언할 경우 Exception을 상속, 실행 예외로 선언할 경우에는RuntimeException을 상속
  • 사용자 정의 예외 클래스 이름은 Exception으로 끝나는 것을 권장
  • 예외 메시지의 용도는 catch {} 블록의 예외처리 코드에서 이용하기 위해서이다..
@Getter
public class CustomException extends RuntimeException implements Serializable {

    private ErrorCode errorCode;

    public CustomException(ErrorCode errorCode) {
        super(errorCode.getMessage());
        this.errorCode = errorCode;
    }
}

여러 커스텀 예외에서 상속받을 CustomException Class를 정의

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum ErrorCode {

    NO_SUCH_USER(400, "U001", "존재하지 않는 사용자 입니다.");

    private int status;
    private final String code;
    private final String message;

    ErrorCode(final int status, final String code, final String message) {
        this.status = status;
        this.code = code;
        this.message = message;
    }

    public int getStatus() {
        return status;
    }

    public String getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

Enum 클래스를 활용해서 에러 코드 관리

public class NoSuchUserException extends CustomException{
    public NoSuchUserException() {
        super(ErrorCode.NO_SUCH_USER);
    }
}

CustomException을 상속받은 예외를 만들어 미리 작성해둔 ErrorCode를 부모클래스를 통해 연결해준다.

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    protected ResponseEntity<?> handleCustomException(CustomException e) {
        log.error(e.getErrorCode() + " : "  + e.getMessage());
        ErrorCode errorCode = e.getErrorCode();
        final ErrorResponse response = ErrorResponse.of(errorCode);
        return new ResponseEntity<>(response, HttpStatus.resolve(errorCode.getStatus()));
    }
}

(Rest)ControllerAdvice는 여러 컨트롤러에 대해 전역적으로 ExceptionHandler를 적용해준다.
위에서 보이듯 ControllerAdvice 어노테이션에는 @Component 어노테이션이 있어서 ControllerAdvice가 선언된 클래스는 스프링 빈으로 등록된다. 그러므로 우리는 다음과 같이 전역적으로 에러를 핸들링하는 클래스를 만들어 어노테이션을 붙여줌으로써 에러 처리를 위임할 수 있다.
이 코드를 통해 log를 찍어주고, 오류 응답을 반환한다.

@Getter
@Setter
@NoArgsConstructor
public class ErrorResponse {

    private String message;
    private String code;
    private int status;

    public ErrorResponse(ErrorCode code) {
        this.message = code.getMessage();
        this.status = code.getStatus();
        this.code = code.getCode();
    }

    public static ErrorResponse of(ErrorCode code) {
        return new ErrorResponse(code);
    }
}

ErrorResponse는 위처럼 구성되어있다.


출처
https://mangkyu.tistory.com/204
https://veneas.tistory.com/entry/Java-%EC%BB%A4%EC%8A%A4%ED%85%80-%EC%98%88%EC%99%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0Custom-Exception

profile
Hello World!!

0개의 댓글