Bootcamp/Web

[Spring] Spring _ Validation, Valid annotation & Exception

K_Hyul 2023. 12. 7. 09:26
728x90

Validation(유효성 검사) - 서비스의 로직이 제대로 동작하기 위해 사용되는 데이터를 사전에 검증하는 작업

이때의 데이터에 대해 의도한 형식의 값이 제대로 들어오는지 체크하는 과정

 

일반적인 유효성 검사

1) 간단한 검증을 해도 검증 관련 로직이 길어짐

2) 검증 로직이 중복으로 존재하게 됨

3) Layer에 검증 로직이 섞여있어 추적이 어렵고 애플리케이션이 복잡해짐

 

if (itemDTO == null) {
    throw new IllegalArgumentException("아이템 정보가 존재하지 않습니다.");
}

if (itemDTO.getItemName() == null || itemDTO.getItemName().isEmpty()) {
    throw new IllegalArgumentException("아이템 명은 필수 입니다.");
}

if (itemDTO.getQuantity() == null) {
    throw new IllegalArgumentException("아이템 개수는 필수 입니다.");
}

 

예시로 이렇게 늘어나게 된다.

 

Java에서는 @Valid를 사용해 유효성 검사를 할 수 있다.

public ResponseEntity<String> save(@Valid @RequestBody ItemDTO itemDTO) {
    itemService.save(itemDTO);
    return new ResponseEntity<>(HttpStatus.CREATED);
}

 

 

@Validation 관련 주요 Annotation(어노테이션){

   @Size : 문자의 길이 조건 

   @NotNull : null 값 불가

   @NotEmpty : @NotNull + empty 불가

   @NotBlank : @NotEmpty + space 값 불가

   @Past : 과거 날짜

   @PastOrPresent : @Past + 오늘 날짜

   @Future : 미래 날짜

   @FutureOrPresent : @Future + 오늘 날짜

   @Pattern : 정규식을 통한 조건

   @Max : 최대값

   @Min : 최소값

   @AssertTrue : 참

   @AssertFalse : 거짓

 

 

public class ProductDto {
  
  private String productId;

  @NotBlank
  @Size(min = 4, max = 10)
  private String ProductName;

  @Min(value = 50)
  private int ProductPrice;

  @Min(value = 0)
  @Max(value = 99)
  private int productStock;

}

 

이렇게 적용할 수 있다.

 

 

Exception 을 정리하자면 

 

@ExceptionHandler를 활용해 Controller 계층에서 발생하는 에러를 잡아서 메서드로 처리

Service, Repository에서 발생하는 에러는 제외

@Controller
public class SimpleController {

    // ...

    @ExceptionHandler
    public ResponseEntity<String> handle(IOException ex) {
        // ...
    }
}

 

 

여러개의 Exception 처리 방법으로는 

@ExceptionHandler의 value 값으로 해당 Exception을 처리할 것인지 넘겨주는데

value를 설정하지 않으면 모든 Exception이 처리가 된다.

위의 이유로 모든 프로그램에서 기본인 Exception을 적용할 때 구체적으로 적어야한다.

 

우선 순위

Exception.class보다 구체적인 오류클래스 NullPointerException.class가 높다.

 

Custom Exception -> 사용자 정의 예외처리

 

@Getter
public class HubException extends Exception {
  
  private HttpStatus httpStatus;

  public HubException(HttpStatus httpStatus, String message) {
    super(message);
    this.httpStatus = httpStatus;
  }
}
728x90

'Bootcamp > Web' 카테고리의 다른 글

[Crawling] 주식 정보  (1) 2024.01.04
[Notalone] mini project (web)  (0) 2023.12.27
[Spring] Spring Security  (0) 2023.12.27
[Front] HTML, CSS  (1) 2023.11.23
[SQL] ERD, MySQL, Docker, DBeaver 설치  (0) 2023.11.17