Home > Net >  @ExceptionHandler method doesn't work when BindingResult parameter present in handler method
@ExceptionHandler method doesn't work when BindingResult parameter present in handler method

Time:11-14

I am validating a field(User) using javax validation api.

User :

@Data
public class User {

    public String name;
    @Min(18)
    public int age;

    public User(String nameString, int age) {
        super();
        this.nameString = nameString;
        this.age = age;
    }
    

Handler method in Controller Class:

@RestController
public class ControllerMain {

    @PostMapping("userdata")
    //Here is BindingResult !!
    public void validdata(@Valid @RequestBody User user,BindingResult bindingResult) {
        
    }
        
}

ControllerAdvice Class for Exception Handling

@ControllerAdvice
public class ExceptionHandlingController {

    @ExceptionHandler({MethodArgumentNotValidException.class, HttpMessageNotReadableException.class})
    public void invalidinput() {
        
        //This should be printed on console but its not.Kindly help!
        System.out.println("Invalid Input!");
    }

}

If I remove the BindingResult argument from handler method in Controller Class 'Invalid Input' is printed on the console. Why so?

CodePudding user response:

It is Spring MVC specification.

1.3.3. Handler Methods > @RequestBody:

You can use @RequestBody in combination with javax.validation.Valid or Spring’s @Validated annotation, both of which cause Standard Bean Validation to be applied. By default, validation errors cause a MethodArgumentNotValidException, which is turned into a 400 (BAD_REQUEST) response. Alternatively, you can handle validation errors locally within the controller through an Errors or BindingResult argument, as the following example shows:

@PostMapping("/accounts")
public void handle(@Valid @RequestBody Account account, BindingResult result) {
    // ...
}
  • Related