본문 바로가기

서버

Springboot3 - Exception 생성하기

728x90

Exception을 Custom 하여 명확한 에러를 처리해보자

 


1. 원하는 Exception class 생성하여 'RuntimeException'을 상속하면 됨

 

public class NotEnoughStockException extends RuntimeException {
 public NotEnoughStockException() {
 }
 public NotEnoughStockException(String message) {
 super(message);
 }
 public NotEnoughStockException(String message, Throwable cause) {
 super(message, cause);
 }
 public NotEnoughStockException(Throwable cause) {
 super(cause);
 }
}

 

2. throw 하는 법

(...생략)

 public void removeStock(int quantity) {
     int restStock = this.stockQuantity - quantity;
     if (restStock < 0) {
     		// >>>>>>>>>>>> 여기
     	throw new NotEnoughStockException("need more stock");
     }
     this.stockQuantity = restStock;
 }
}

(...생략)