[Spring Boot] 타입 불일치, Redis 통합

D3F D3V J30N·2025년 1월 8일
0

Error

목록 보기
3/4
post-thumbnail

1. 첫 번째 오류: 타입 불일치

error: incompatible types: ProductItem cannot be converted to Product
.addProductItem(provider.getUserVo(token).getId(), form)));
  • 원인
    ProductItemServiceaddProductItem 메서드가 Product를 반환하도록 정의되었으나, 실제로는 ProductItem을 반환하고 있었다. 이로 인해 컨트롤러에서 응답 타입이 일치하지 않는 문제가 발생했다.

  • 해결 방법

    • SellerProductController의 응답 타입을 ProductDto에서 ProductItemDto로 변경.
    • ProductItemDto 클래스 추가하여 ProductItem 엔티티를 DTO로 변환하도록 구현.
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ProductItemDto {
    private Long id;
    private String name;
    private int price;
    private int count;

    public static ProductItemDto from(ProductItem item) {
        return ProductItemDto.builder()
                .id(item.getId())
                .name(item.getName())
                .price(item.getPrice())
                .count(item.getCount())
                .build();
    }
}

2. 두 번째 오류: 누락된 클래스

error: cannot find symbol
import com.zerobase.cms.order.service.CartService;
  • 원인
    CartService 클래스가 구현되지 않았습니다. 또한 Redis와 연동하기 위한 클라이언트 인터페이스도 정의되지 않아 오류가 발생했다.

  • 해결 방법

    • CartService 클래스 구현.
    • Redis와의 통신을 위한 RedisClient 인터페이스 생성.
    • 장바구니 관련 비즈니스 로직을 담당하는 CartApplication 클래스 구현.
public interface RedisClient {
    void put(String key, Object value);
    <T> T get(String key, Class<T> clazz);
}
@Service
public class CartService {
    private final RedisClient redisClient;

    public CartService(RedisClient redisClient) {
        this.redisClient = redisClient;
    }

    public Cart getCart(String customerId) {
        return redisClient.get(customerId, Cart.class);
    }
}

3. 세 번째 오류: 누락된 에러 코드

error: cannot find symbol
symbol: variable ORDER_FAIL_CHECK_CART
location: class ErrorCode
  • 원인
    에러 코드가 정의된 ErrorCode enum에 필요한 값이 누락되어 있었다.

  • 해결 방법
    ErrorCode enum에 필요한 에러 코드를 추가하여 누락된 값들을 보완했다.

public enum ErrorCode {
    NOT_FOUND_PRODUCT(HttpStatus.BAD_REQUEST, "상품을 찾을 수 없습니다."),
    CART_CHANGE_FAIL(HttpStatus.BAD_REQUEST, "장바구니에 추가할 수 없습니다."),
    ORDER_FAIL_CHECK_CART(HttpStatus.BAD_REQUEST, "주문 불가! 장바구니를 확인해 주세요."),
    ORDER_FAIL_NO_MONEY(HttpStatus.BAD_REQUEST, "주문 불가! 잔액 부족입니다.");
}

4. 네 번째 오류: CustomException 응답 처리 부족

error: cannot find symbol
CustomException.CustomExceptionResponse
  • 원인
    CustomException 클래스에 응답 처리를 위한 내부 클래스가 구현되지 않아 예외 처리 로직에서 오류가 발생했다.

  • 해결 방법
    CustomException 클래스에 내부 클래스 CustomExceptionResponse를 추가하고, 이를 통해 클라이언트에 예외 응답을 반환하도록 처리했다.

@AllArgsConstructor
@Builder
@NoArgsConstructor
@Getter
public static class CustomExceptionResponse {
    private int status;
    private String code;
    private String message;
}
@RestControllerAdvice
public class ApiExceptionAdvice {
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<CustomExceptionResponse> handleCustomException(CustomException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(CustomExceptionResponse.builder()
                        .status(HttpStatus.BAD_REQUEST.value())
                        .code(ex.getErrorCode().name())
                        .message(ex.getErrorCode().getMessage())
                        .build());
    }
}

5. 다섯 번째 오류: 잘못된 어노테이션 사용

warning: @Builder.Default requires @Builder or @SuperBuilder
  • 원인
    @Builder.Default 어노테이션을 사용하려면 클래스에 @Builder 또는 @SuperBuilder가 필요하다. 해당 어노테이션이 누락되어 경고가 발생했다.

  • 해결 방법
    장바구니를 관리하는 Cart 클래스에 @Builder 어노테이션을 추가했다.

@Builder
public class Cart {
    @Builder.Default
    private List<Product> products = new ArrayList<>();
}

프로젝트 개선사항

  1. 도메인 구조 개선

    • Product, ProductItem, Cart 등 엔티티를 체계적으로 설계하여 재사용성과 확장성을 높였다.
  2. Redis 통합

    • Redis 클라이언트를 추상화하여 데이터 저장 및 조회 로직을 분리했다.
    • Redis와 장바구니 기능을 통합하여 빠르고 효율적인 데이터 관리를 구현했다.
  3. 일관된 예외 처리

    • 모든 예외를 CustomException으로 통합.
    • ErrorCode enum을 활용해 명확한 에러 메시지와 상태 코드를 제공.
    • ApiExceptionAdvice로 글로벌 예외 처리 로직을 구현.
  4. 테스트 코드 개선

    • Redis와 통합된 장바구니 기능의 테스트 케이스 작성.
    • Mock 객체를 활용하여 서비스 레이어의 단위 테스트 작성.

인사이트

프로젝트 진행 과정에서 여러 오류를 경험했지만, 이를 해결하며 시스템을 더욱 견고하게 만들 수 있었다. 특히 Redis 통합, 일관된 예외 처리, 테스트 코드 개선은 프로젝트의 안정성과 유지보수성을 크게 향상시켰다. 앞으로도 이러한 경험을 바탕으로 더 나은 코드를 작성해 나가야겠다.

오늘의 명언

"자신을 어떻게 생각하느냐가

자신의 운명을 결정짓는다."

-헨리 데이비드 소로-

profile
Problem Solver

0개의 댓글