2016-04-11 16 views
7

Quando il "nome" PathVariable non supera la convalida viene generata una javax.validation.ConstraintViolationException. C'è un modo per recuperare il nome del parametro nella gettata javax.validation.ConstraintViolationException?Ottieni nome campo quando viene generata 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

Forse ci lavori? – ptimson

risposta

5

il seguente gestore delle eccezioni mostra come funziona:

@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); 

} 

È possibile accedere al valore non valido (nome) con

constraintViolation.getInvalidValue() 

È possibile accedere al nome della proprietà 'name' con

constraintViolation.getPropertyPath() 
+0

Grazie Stefan, ma sto cercando di ottenere il nome del parametro, non il valore. Nell'esempio sopra mi piacerebbe accedere a "nome". – Josh

+0

aggiunto come ottenere il 'nome' –

+7

Ho provato a farlo ma getPropertyPath restituisce sayHi.arg0 – Josh

2

Ho avuto t ha lo stesso problema ma ha anche ottenuto "sayHi.arg0" da getPropertyPath. Ho scelto di aggiungere un messaggio alle annotazioni NotNull poiché facevano parte della nostra API pubblica. Come:

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

è possibile ottenere il messaggio chiamando

ConstraintViolation # getMessage()

1

uso questo metodo (ex è esempio 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()); 


    } 
Problemi correlati