我有一个如下所示的 pojo(请假设一个 Controller 和其余代码。应用程序位于 Spring boot 中):
@Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public class User {
@NotBlank(message = "userName is blank")
private String userName;
@NotBlank(message = "secretKey is blank")
private String secretKey;
}
并定义了一个带有@ControllerAdvice
注释的ExceptionHandler类,并定义了一个方法,如下所示:
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = {MethodArgumentNotValidException.class})
protected ResponseEntity<ErrorResponse> handleMethodArgNotValidException(MethodArgumentNotValidException ex,Locale locale) {
// code to handle exception.
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = {WebExchangeBindException.class})
protected ResponseEntity<ErrorResponse> handleException(WebExchangeBindException ex, Locale locale) {
// code to handle exception.
}
但在这种情况下,即使两个字段都有验证错误,客户端也只能得到一个。
我想问有什么办法可以列出该端点响应中的所有验证错误吗?
curl --location --request POST 'localhost/api/login' \
--header 'Content-Type: application/json' \
--data-raw '{
"userName": null,
"secretKey": null
}'
最佳答案
您可以从 MethodArgumentNotValidException
获取 BindingResult
,然后根据所有拒绝的字段撰写消息,例如:
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = {MethodArgumentNotValidException.class})
protected ResponseEntity<ErrorResponse> handleMethodArgNotValidException(MethodArgumentNotValidException ex, Locale locale) {
String errorMessage = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
.collect(Collectors.joining("; "));
// put errorMessage into ErrorResponse
// return ResponseEntity<ErrorResponse>
}
}
可能的消息输出示例:
{
"timestamp": "2022-01-28T17:18:53.1738558+03:00",
"status": 400,
"error": "BadRequest",
"errorMessage": "userName: userName is blank; secretKey: secretKey is blank"
}
关于java - 我可以获得 Spring Boot Web 应用程序中的所有验证错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70894623/