您好,我是 Java 初学者,使用 SpringBoot 验证 javax 时遇到问题。我创建了自己的 ExceptionHandler 来处理验证异常:MethodArgumentNotValidException
当请求无效时抛出。
无效的 JSON 请求示例:
{
"code": "",
"name": ""
}
控制器:
@Controller
@RequestMapping("/v1/api")
public class ApiController {
@Autowired
private Service service;
@PostMapping("/")
public ResponseEntity<?> returnHomePage(@Valid @RequestBody RequestDTO requestDTO) {
return ResponseEntity.ok().body(service.getSomeData(requestDTO));
}
}
带有 javax 验证注释的类:
@Data
public class RequestDTO {
@NotBlank(message = "Return code is a required field")
@Size(min = 6, max = 10, message = "Return code must be in range 6-10 digits")
@Pattern(regexp = "[\\d]{6,10}", message = "Return code must be numeric")
private String code;
@NotBlank(message = "Name is a required field")
@Size(min = 1, max = 15, message = "Name must be in range 1-15 digits")
private String name;
}
我的处理程序中的方法:
@ExceptionHandler(value = {MethodArgumentNotValidException.class})
public ResponseEntity<Object> handleBadRequestException(MethodArgumentNotValidException ex, WebRequest request) {
List<String> errorMessages = new ArrayList<>();
Map<String, List<String>> details = ex
.getBindingResult()
.getFieldErrors()
.stream()
.collect(Collectors.toMap(FieldError::getField, fieldError -> {
errorMessages.add(fieldError.getDefaultMessage());
return errorMessages;
}, (key, duplicatedKey) -> key));
ErrorMessage errorMessage = new ErrorMessage(HttpStatus.BAD_REQUEST.name().toLowerCase(), ex.getMessage(), details);
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
错误消息类:
@Data
@AllArgsConstructor
public class ErrorMessage {
private final String key;
private final String msg;
private final Map<String, List<String>> details;
}
我想要实现的是获得每个字段的嵌套验证错误,如下例所示:
{
"key": "bad_request",
"msg": "Validation errors occurred",
"details": {
"code": [
"Return code must be numeric",
"Return code must be in range 6-10 digits",
"Return code is a required field",
],
"name": [
"Name must be in range 1-15 digits",
"Name is a required field",
]
}
}
我在这一点上得到了什么:
{
"key": "bad_request",
"msg": "Validation errors occurred",
"details": {
"code": [
"Return code is a required field",
"Name is a required field",
"Return code must be in range 6-10 digits",
"Name must be in range 1-15 digits",
"Return code must be numeric"
],
"name": [
"Return code is a required field",
"Name is a required field",
"Return code must be in range 6-10 digits",
"Name must be in range 1-15 digits",
"Return code must be numeric"
]
}
}
正如您所看到的,代码和名称键在这两个字段中都出现验证错误,这是错误的 :) 我将不胜感激任何帮助 :)