처음부터 차근차근

custom exception 본문

Framework/Spring

custom exception

_soyoung 2022. 9. 13. 18:45
반응형

exception을 커스텀해서 만드는 방법

1. 클래스 생성

 

2. RuntimeException class 상속받고, 생성자를 정의한다.

public class CRUDFailException extends RuntimeException {
    public CRUDFailException(String message) {
        super(message); // RuntimeException 클래스의 생성자를 호출합니다.
    }
}

 

3. controller advice에서 예외를 받아 처리할 로직을 작성한다.

@ControllerAdvice
public class ExceptionController {
    ...
    @ExceptionHandler(CRUDFailException.class)
    protected String handleCRUDFailExceptionException(Exception e) {
        // 에러 코드 작성
        return e.getMessage(); // 에러 메세지 return
    }
}

 

4. 예외를 throw 해서 사용한다.

throw new CRUDFailException("예외 발생!!!!!");

 

 

반응형
Comments