简体   繁体   中英

ValidationException vs ConstraintViolationException for validation

I am trying to figure out which Exception ( ConstraintViolationException or ValidationException ) i have to used on @ControllerAdvice , .

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
    public class ValidationAdviceClass{
        @ExceptionHandler(ValidationException.class or ConstraintViolationException.class )
        public ResponseEntity handleValidtionErrors(ValidationException ex or ConstraintViolationException) {

       // mycode
}

Searching i found someone saying use 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).

Any validation errors in your RequestBody would be passed to the BindingResult that you also have as a parameter of your function. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM