ErrorCode 작성하기
@Getter
public enum ErrorCode {
ITEM_PRICE(400, "ITEM-001", "아이템 가격이 1000원 넘음");
private final int status;
private final String code;
private final String description;
ErrorCode(int status, String code, String description) {
this.status = status;
this.code = code;
this.description = description;
}
}
exception 커스텀하기 (예외 클래스 만들기)
public class ItemPriceException extends RuntimeException {
private static final ErrorCode errorCode = ErrorCode.ITEMPRICE;
public ItemPriceException(String message) {
super(message);
}
public ErrorCode getErrorCode() {
return errorCode;
}
}
서비스단에서 예외 발생하는 곳에 예외 던져 주기
if(itemPrice > 10000)
throw new ItemPriceException("아이템 에러");
ExceptionHandler에서 handleException 작성
<-- ErrorResponse -->
public record ErrorResponse(String code, String message) {}
<-- GlobalExceptionHandler -->
@ExceptionHandler(ItemPriceException.class)
public ResponsEntity<ErrorResponse> handleItemPriceException(ItemPriceException e) {
ErrorCode errorCode = e.getErrorCode();
ErrorResponse errorResponse = new ErrorResponse(errorCode.getCode(), e.getMessage());
return ResponseEntity.status(errorCode.getStatus()).body(errorResponse);
}
프론트에서 post 넘겨 받을 때 error 처리
catch(error => {
console.log(error.response.data.code);
console.log(error.response.data.message);
alarm ({
title: error.response.data.code,
text: error.reponse.data.message,
icon: 'warning'
});
}