복붙노트

[SPRING] javax.validation.ConstraintViolationException가 슬로우 될 때 필드 이름 가져 오기

SPRING

javax.validation.ConstraintViolationException가 슬로우 될 때 필드 이름 가져 오기

PathVariable 'name'이 유효성 검사를 통과하지 못하면 javax.validation.ConstraintViolationException이 발생합니다. throw 된 javax.validation.ConstraintViolationException에서 매개 변수 이름을 검색하는 방법이 있습니까?

@RestController
@Validated
public class HelloController {

@RequestMapping("/hi/{name}")
public String sayHi(@Size(max = 10, min = 3, message = "name should    have between 3 and 10 characters") @PathVariable("name") String name) {
  return "Hi " + name;
}

해결법

  1. ==============================

    1.다음 Exception Handler는 어떻게 작동하는지 보여줍니다 :

    다음 Exception Handler는 어떻게 작동하는지 보여줍니다 :

    @ExceptionHandler(ConstraintViolationException.class)
    
    ResponseEntity<Set<String>> handleConstraintViolation(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
    
    Set<String> messages = new HashSet<>(constraintViolations.size());
    messages.addAll(constraintViolations.stream()
            .map(constraintViolation -> String.format("%s value '%s' %s", constraintViolation.getPropertyPath(),
                    constraintViolation.getInvalidValue(), constraintViolation.getMessage()))
            .collect(Collectors.toList()));
    
    return new ResponseEntity<>(messages, HttpStatus.BAD_REQUEST);
    
    }
    

    잘못된 값 (이름)에 액세스 할 수 있습니다.

     constraintViolation.getInvalidValue()
    

    'name'속성 이름에 액세스 할 수 있습니다.

    constraintViolation.getPropertyPath()
    
  2. ==============================

    2.이 메소드를 사용한다 (예 : ConstraintViolationException 인스턴스).

    이 메소드를 사용한다 (예 : ConstraintViolationException 인스턴스).

    Set<ConstraintViolation<?>> set =  ex.getConstraintViolations();
        List<ErrorField> errorFields = new ArrayList<>(set.size());
        ErrorField field = null;
        for (Iterator<ConstraintViolation<?>> iterator = set.iterator();iterator.hasNext(); ) {
            ConstraintViolation<?> next =  iterator.next();
           System.out.println(((PathImpl)next.getPropertyPath())
                    .getLeafNode().getName() + "  " +next.getMessage());
    
    
        }
    
  3. ==============================

    3.나는 같은 문제가 있었지만 getPropertyPath에서 "sayHi.arg0"을 얻었다. NotNull 주석은 공개 API의 일부이므로 NotNull 주석에 메시지를 추가하기로했습니다. 처럼:

    나는 같은 문제가 있었지만 getPropertyPath에서 "sayHi.arg0"을 얻었다. NotNull 주석은 공개 API의 일부이므로 NotNull 주석에 메시지를 추가하기로했습니다. 처럼:

     @NotNull(message = "timezone param is mandatory")
    

    너는 부름으로써 메시지를 얻을 수있다.

  4. ==============================

    4.getPropertyPath ()의 반환 값을 검사하면 iterable Iterable 이고 iterator의 마지막 요소는 필드 이름입니다. 다음 코드는 나를 위해 작동합니다.

    getPropertyPath ()의 반환 값을 검사하면 iterable Iterable 이고 iterator의 마지막 요소는 필드 이름입니다. 다음 코드는 나를 위해 작동합니다.

    // I only need the first violation
    ConstraintViolation<?> violation = ex.getConstraintViolations().iterator().next();
    // get the last node of the violation
    String field = null;
    for (Node node : violation.getPropertyPath()) {
        field = node.getName();
    }
    
  5. from https://stackoverflow.com/questions/36555057/get-field-name-when-javax-validation-constraintviolationexception-is-thrown by cc-by-sa and MIT license