How do I customize default error message from spring @Valid validation?

前端 未结 10 854
孤街浪徒
孤街浪徒 2020-12-22 23:04

DTO:

public class User {

    @NotNull
    private String name;

    @NotNull
    private String password;

    //..
}

Controller:

10条回答
  •  独厮守ぢ
    2020-12-22 23:32

    One way to do it is adding message in @NotNull annotation on entity properties. And adding @Valid annotation in controller request body.

    DTO:

    public class User {
       
        @NotNull(message = "User name cannot be empty")
        private String name;
    
        @NotNull(message = "Password cannot be empty")
        private String password;
    
        //..
    }
    

    Controller:

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public ResponseEntity saveUser(@Valid @RequestBody User user) {
        //..
        return new ResponseEntity<>(HttpStatus.OK);
    }
    // Add one 
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity> handleException(MethodArgumentNotValidException ex) {
    // Loop through FieldErrors in ex.getBindingResult();
    // return *YourErrorReponse* filled using *fieldErrors*
    }
    

提交回复
热议问题