개발/부트캠프

본캠프 : methodargumentnotvalidexception

EJ EJ 2025. 3. 27. 13:30

[ MethodArgumentNotValidException은 @Valid 또는 @Validated 검증 실패 시 발생하는 예외 처리 ]

@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    for (FieldError error : ex.getBindingResult().getFieldErrors()) {
        errors.put(error.getField(), error.getDefaultMessage());
    }
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
}

 

  • getBindingResult().getFieldErrors()를 사용하여 어떤 필드에서 오류가 발생했는지, 오류 메시지는 무엇인지 수집합니다.
  • Map<String, String>을 반환하여 필드명과 오류 메시지를 JSON 형태로 응답합니다.
  • HTTP 상태 코드 400(BAD_REQUEST) 를 반환합니다.