我有 Controller 建议:
@ExceptionHandler(ConstraintViolationException.class)
ResponseEntity<String> handleConstraintViolationException(ConstraintViolationException constraintViolationException) {
return new ResponseEntity<>(constraintViolationException.getMessage(), HttpStatus.BAD_REQUEST);
}
我有一个 Controller :
@PostMapping(value="linkSellerBuyer")
@Validated
public String createSellerBuyer(Seller seller, Buyer buyer) {
// some code
return "some response";
}
每个模型都是这样的:
public class Seller {
@NotEmpty String Email;
// and more and more
}
public class Buyer {
@NotEmpty String Email;
// and more and more
}
我得到的错误是我总是同时遇到卖家和买家错误
例如: 卖家:不能为空,买家:不能为空,我想要的是 卖家:不能为空
?我如何为此创建代码?
最佳答案
如果您check this out您将看到它立即验证所有参数。
但如果您确实只想要一条且第一条消息,您可以将其提取到 handleConstraintViolationException
中:
@ExceptionHandler(ConstraintViolationException.class)
ResponseEntity<String> handleConstraintViolationException(ConstraintViolationException constraintViolationException) {
return new ResponseEntity<>(constraintViolationException.getConstraintViolations()
.iterator().next().getMessage(),
HttpStatus.BAD_REQUEST);
}
关于java - 如何在 Spring Boot 中的第一个约束后停止进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60494386/