본문 바로가기

TIL

@Valid @NotEmpty

예외처리중에 DB를 가기전에 예외처리를 해줘야하는 상황이 생각이났다. 게시글에 댓글이나 게시글을 저장하기위해서는 내용이 필수적으로 필요하다 빈값이 들어오면 DB에 접근하기전에 미리 예외를 처리해주어야하는 상황이지 않을까 생각이 들었다.

@PostMapping("api/comments/{postId}")
public ResponseEntity<CommentDto> postComment(@PathVariable Long postId, @Valid @RequestBody CommentRequestDto requestDto) {
    CommentDto response = commentService.save(requestDto, postId);
    return ResponseEntity.ok(response);
}

Controller로 들어온 Request가 유효한지 판단하는 어노테이션인@Valid이다.

 

@Getter
public class CommentRequestDto {
    private String username;

    @NotBlank(message = "내용을입력하세요")
    private String contents;
}

Request중 contents의 값은 필수적이기 때문에 @NotBlank를 사용해주어 만약 빈값이 들어온다면 

예외상황 처리가 되어 errorhandler를 통해 내용을 입력하세요라는 메시지가 담긴 ResponseEntity 객체를 생성하여 응답하게 된다.

@RestControllerAdvice
public class ErrorHandler {
    // Bean Validation에서 터지는 에러
    @ResponseStatus(HttpStatus.BAD_REQUEST) // 400
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public NotValidResponse notValid(MethodArgumentNotValidException e) {
        // 오류난 입력값이 여러개여도 하나씩만 보여준다.
        FieldError fieldError = e.getBindingResult().getFieldErrors().get(0);
        return NotValidResponse.builder()
                .field(fieldError.getField())               // 오류난 필드명
                .value(fieldError.getRejectedValue())       // 거절된 입력된 값
                .message(fieldError.getDefaultMessage())    // 내가 설정한 메시지
                .build();
    }

 

package com.sparta.board.common.error;

import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class NotValidResponse {
    private String field;
    private Object value;
    private String message;
}

 빈값을 체크하는 어노테이션은

NotNull : null만 허용하지 않게 한다.

NotEmpty :  null  "" 둘 다 허용하지 않게 합니다.

NotBlank : null, "", " "셋다 허용하지 않게 합니다.

 

 

 

https://sanghye.tistory.com/36

 

[Spring Boot] @NotNull, @NotEmpty, @NotBlank 의 차이점 및 사용법

개발하시는 API 의 request parameter 의 null 체크를 어떻게 하고 계신가요? 대부분 별도의 null 체크 util 을 사용하거나, Controller 에서 조건문을 사용하여 null 을 체크하기도 합니다. 이러한 조건문과 메

sanghye.tistory.com

 

'TIL' 카테고리의 다른 글