[英]ValidationException vs ConstraintViolationException for validation
I am trying to figure out which Exception ( ConstraintViolationException
or ValidationException
) i have to used on @ControllerAdvice
, . 我试图弄清楚我必须在
@ControllerAdvice
上使用哪个异常( ConstraintViolationException
或ValidationException
)。
My controller is 我的控制器是
@RequestMapping(value="/myUrl",method = RequestMethod.POST)
public String getMyData( @Valid @RequestBody MyObject myObject,BindingResult bindingResult ) {
And this is my ControllerAdvice class and i am not sure which exception to use. 这是我的ControllerAdvice类,我不确定要使用哪个异常。
@ControllerAdvice
public class ValidationAdviceClass{
@ExceptionHandler(ValidationException.class or ConstraintViolationException.class )
public ResponseEntity handleValidtionErrors(ValidationException ex or ConstraintViolationException) {
// mycode
}
Searching i found someone saying use MethodArgumentNotValidException
搜索我发现有人说使用
MethodArgumentNotValidException
I am confused with which type of exception to use. 我对使用哪种类型的异常感到困惑。
No exception is automatically thrown unless an error happened during the process of validation, for example (then a ValidationException
would be thrown). 除非在验证过程中发生错误,否则不会自动引发异常(例如,将引发
ValidationException
)。
Any validation errors in your RequestBody
would be passed to the BindingResult
that you also have as a parameter of your function. RequestBody
任何验证错误都将传递给BindingResult
,您也将其作为函数的参数。 Then it's up to you to decide if you want to throw an exception. 然后由您决定是否要引发异常。
I suggest you read this Spring Tutorial about Validating Form Input to better understand how you can achieve what you want. 我建议您阅读有关验证表单输入的本Spring教程,以更好地了解如何实现所需的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.