gpt4 book ai didi

java - 验证失败时在 Spring RestController 中抛出什么类型的异常?

转载 作者:IT老高 更新时间:2023-10-28 13:45:30 25 4
gpt4 key购买 nike

在 Spring RestController 中,我只需将相应的方法参数注释为 @Valid 即可对 RequestBody 进行输入验证@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);
}

最佳答案

对我来说,最简单的方法是使用错误对象验证对象,然后在 MethodArgumentNotValidException 中使用它。

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> createOrder(@RequestBody @Validated(InputChecks.class) Order order)
throws NoSuchMethodException, SecurityException, MethodArgumentNotValidException {
// Some processing of the Order goes here
SpringValidatorAdapter v = new SpringValidatorAdapter(validator);
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(order, "order");
v.validate(order, errors, FinalChecks.class);
if (errors.hasErrors()) {
throw new MethodArgumentNotValidException(
new MethodParameter(this.getClass().getDeclaredMethod("createOrder", Order.class), 0),
errors);
}
orders.put(order);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/" + order.getId()).build().toUri());
return new ResponseEntity<>(null, headers, HttpStatus.CREATED);
}

这样,在第二个验证步骤中发现的错误与在@validated 参数的输入验证过程中发现的错误具有完全相同的结构。

关于java - 验证失败时在 Spring RestController 中抛出什么类型的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35766872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com