当验证失败时,在 Spring RestController 中引发什么类型的异常?
2022-09-02 20:35:03
在 Spring 中,我通过简单地将相应的方法参数注释为 or 来输入验证 。其他一些验证只能在对传入数据进行一些处理后执行。我的问题是,我应该使用什么类型的异常,以便它类似于注释引发的异常,以及如何从验证结果构造此异常。下面是一个示例:RestController
RequestBody
@Valid
@Validated
@Valid
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> createOrder(@RequestBody @Validated(InputChecks.class) Order order) {
// Some processing of the Order goes here
Set<ConstraintViolation<Order>> violations = validator.validate(order, FinalChecks.class);
// What to do now with the validation errors?
orders.put(order);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/" + order.getId()).build().toUri());
return new ResponseEntity<>(null, headers, HttpStatus.CREATED);
}