Skip to content

Commit

Permalink
feat: Validation 처리를 위한 에러 handle 추가 (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
kyeong-hyeok committed Dec 5, 2023
1 parent 6b35197 commit 4646dbb
Showing 1 changed file with 18 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,16 @@
import com.project.mapdagu.error.exception.custom.TokenException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

import static org.springframework.http.HttpStatus.BAD_REQUEST;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
Expand All @@ -30,4 +37,15 @@ public ResponseEntity<ErrorResponse> handle(final TokenException e) {
return ResponseEntity.status(e.getCode()).body(ErrorResponse.of(e.getCode(), e.getMessage()));
}

@ExceptionHandler
public ResponseEntity<ErrorResponse> handle(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
// 에러 반환이 여러 개일 경우 첫 번째 에러를 반환
String firstErrorMessage = bindingResult.getFieldErrors().get(0).getDefaultMessage();
// 모든 에러 메시지는 로그로 남김
List<String> errorList = bindingResult.getFieldErrors().stream().map(err -> err.getDefaultMessage()).collect(Collectors.toList());
log.warn("MethodArgumentNotValidExceptionException = {}", errorList);

return ResponseEntity.status(BAD_REQUEST).body(ErrorResponse.of(e.getStatusCode().value(), firstErrorMessage));
}
}

0 comments on commit 4646dbb

Please sign in to comment.