Hello everyone, I have a question
1. Environment
spring 4.3.7 hibernate-validator-5.4.1
2. The configuration is as follows
classpath:messages/messages classpath:messages/ValidationMessages
3.bean and Controller
public class UserRequest { @NotBlank(message = "{login.valid.username.notnull}") private String username; @NotBlank(message = "{login.valid.password.notnull}") private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
@RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public Object login(@Valid @RequestBody UserRequest ur, BindingResult result, HttpServletRequest request) { log.debug("login"); if(result.hasErrors()) { return result.getAllErrors().get(0); } …… }
Question:
Why must we use result.hasErrors() to display judgment in the code?
Isn’t it more reasonable to verify that the fields in UserRequest do not meet the definition and just throw an exception directly?
Question:
Why must we use result.hasErrors() to display judgment in the code?
Isn’t it more reasonable to verify that the fields in UserRequest do not meet the definition and just throw an exception directly?
For example, when a parameter exception occurs, what we return to the front end is the specific parameter name and description of the exception, not all the exception information given by Spring. If Spring automatically throws an exception, then it is difficult for you to control the returned information.
You just consider why in your application scenario. A framework is more about considering what is most reasonable most of the time.
Most validations of client data should not be considered "abnormalities", but errors that users are allowed to make without knowing it.