[SPRING] 예외처리 해보기 v1

박진서·2023년 6월 20일
0

Spring

목록 보기
9/13
  1. ErrorCode 작성하기

    • enum 클래스
    • int status, String code, String description
    @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;
        }
    }
  2. exception 커스텀하기 (예외 클래스 만들기)

    public class ItemPriceException extends RuntimeException {
    	private static final ErrorCode errorCode = ErrorCode.ITEMPRICE;
        
        public ItemPriceException(String message) {
        	super(message);
        }
        public ErrorCode getErrorCode() {
        	return errorCode;
        }
    }
  3. 서비스단에서 예외 발생하는 곳에 예외 던져 주기

    • throw new Exception("Message")
    if(itemPrice > 10000) 
    	throw new ItemPriceException("아이템 에러");
  4. ExceptionHandler에서 handleException 작성

    • ErrorResponse로 프론트로 넘겨주기
    <-- 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);
    }
  5. 프론트에서 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'
    	});
    }
profile
백엔드 개발자

0개의 댓글