Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

Kim ByeungHyun

예외처리 + 관심사 별로 분리 본문

Framework/Spring

예외처리 + 관심사 별로 분리

sandbackend 2022. 10. 11. 02:28

Product 생성자

public Product(ProductRequestDto requestDto, Long userId) {
    if (userId == null || userId <= 0) {
        throw new IllegalArgumentException("회원 Id 가 유효하지 않습니다.");
    }

    if (requestDto.getTitle() == null || requestDto.getTitle().isEmpty()) {
        throw new IllegalArgumentException("저장할 수 있는 상품명이 없습니다.");
    }

    if (!URLValidator.isValidUrl(requestDto.getImage())) {
        throw new IllegalArgumentException("상품 이미지 URL 포맷이 맞지 않습니다.");
    }

    if (!URLValidator.isValidUrl(requestDto.getLink())) {
        throw new IllegalArgumentException("상품 최저가 페이지 URL 포맷이 맞지 않습니다.");
    }

    if (requestDto.getLprice() <= 0) {
        throw new IllegalArgumentException("상품 최저가가 0 이하입니다.");
    }

    // 관심상품을 등록한 회원 Id 저장
    this.userId = userId;
    this.title = requestDto.getTitle();
    this.image = requestDto.getImage();
    this.link = requestDto.getLink();
    this.lprice = requestDto.getLprice();
    this.myprice = 0;
}

 

ProductValidator 클래스를 생성하여 분리가능 / : 관심상품 저장 Input에 대한 Valiation 에만 관심이 있는 클래스

@Component
public class ProductValidator {
    public static void validateProductInput(ProductRequestDto requestDto, Long userId) {
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("회원 Id 가 유효하지 않습니다.");
        }

        if (requestDto.getTitle() == null || requestDto.getTitle().isEmpty()) {
            throw new IllegalArgumentException("저장할 수 있는 상품명이 없습니다.");
        }

        if (!URLValidator.isValidUrl(requestDto.getImage())) {
            throw new IllegalArgumentException("상품 이미지 URL 포맷이 맞지 않습니다.");
        }

        if (!URLValidator.isValidUrl(requestDto.getLink())) {
            throw new IllegalArgumentException("상품 최저가 페이지 URL 포맷이 맞지 않습니다.");
        }

        if (requestDto.getLprice() <= 0) {
            throw new IllegalArgumentException("상품 최저가가 0 이하입니다.");
        }
    }
}

 

ProductValidator 적용

// 관심 상품 생성 시 이용합니다.
public Product(ProductRequestDto requestDto, Long userId) {
    // 입력값 Validation
    ProductValidator.validateProductInput(requestDto, userId);

    // 관심상품을 등록한 회원 Id 저장
    this.userId = userId;
    this.title = requestDto.getTitle();
    this.image = requestDto.getImage();
    this.link = requestDto.getLink();
    this.lprice = requestDto.getLprice();
    this.myprice = 0;
}

 

 

'Framework > Spring' 카테고리의 다른 글

QueryDSL  (1) 2023.05.21
IoC DI 강의  (1) 2022.10.17
AOP, 예외처리, Transaction  (0) 2022.10.11
JPA 심화  (0) 2022.10.10
Dto를 거쳐 Controller, Repository  (0) 2022.10.07