@ControllerAdvice 어노테이션을 단 GlobalExceptionHandler 클래스를 만들어서 예외 발생시 잡을 수 잇게 할 수 있다.
그러나 이러면 예외가 많아지면 처리하기 힘든데, 이는 RuntimeException을 extends 해서 처리 할 수 있다.
(RuntimeException 쓰는 이유 : 가장 포괄적이라)
public class ServiceException extends RuntimeException{
private String resultCode;
private String msg;
public ServiceException(String resultCode, String msg) {
super("%s : %s".formatted(resultCode, msg));
this.resultCode = resultCode;
this.msg = msg;
}
public String getResultCode() {
return resultCode;
}
public String getMsg() {
return msg;
}
}
위와 같이 엔티티 하나 만들고
@ControllerAdvice 어노테이션 단 에러 처리하는 놈에게
@ExceptionHandler(ServiceException.class)
@ResponseBody
public RsData<Void> handleException(ServiceException e) {
return new RsData<Void>(
e.getResultCode(),
e.getMsg()
);
}
이렇게 처리하라고 하면
throw new ServiceException("에러코드","에러 메시지");
이런식으로 사용 가능!
extends 한게 런타임이라서 예외 잡는 놈도 런타임을 잡게 하면 된다.