Spring boot ConstraintViolationException返回HashMap字段名和消息



对于ConstraintViolationException,我想返回HashMap<String,String>与fieldName和消息我这样写:

@ExceptionHandler(ConstraintViolationException.class)
ResponseEntity<HashMap<String,String>> handleConstraintViolation(ConstraintViolationException e) {
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
Set<String> errorName = new HashSet<>(constraintViolations.size());
Set<String> messages = new HashSet<>(constraintViolations.size());
messages.addAll(constraintViolations.stream()
.map(violation -> String.format("%s", violation.getMessage())).toList());
errorName.addAll(constraintViolations.stream()
.map(violation -> String.format("%s", StreamSupport.stream(violation.getPropertyPath().spliterator(), false).reduce((first, second) -> second).orElse(null))).toList());
HashMap<String,String> errors = new HashMap<>();
errors.put(errorName.toString(), messages.toString());
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}

返回:

[producent, name, description, image]
:[type correct productent, type correct product image, type correct desc, type correct image]

我想让它返回:

producent : "type correct productent",
name : "type correct image",
description : "type correct desc",
image : "type correct image"
我不知道我该怎么做,有人能帮我吗?

您想在map中获得多个键,但只需添加一个。

试试这个:

@ExceptionHandler(ConstraintViolationException.class)
ResponseEntity<HashMap<String, String>> handleConstraintViolation(ConstraintViolationException e) {
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
HashMap<String, String> errors = new HashMap<>();
constraintViolations.forEach(violation ->
errors.put(
violation.getPropertyPath().toString(),
violation.getMessage()));
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}

最新更新