About the encapsulation of @ RequestBody default exception information

public JsonResult add(@RequestBody(required = false) User user){
    if(user == null){
        //  RequestBody ;
        // ;
    }
}

use @ ControllerAdvice for uniform exception handling


Spring provides its own parameter verification mechanism
validation class

public class UserValidator implements Validator {
    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(User.class);
    }

    @Override
    public void validate(Object o, Errors errors) {
        if (o == null) {
            errors.rejectValue("", null, "");
        }
    }
}

UserController

public class UserController {
    /**
     *  @Valid
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // 
        binder.setValidator(new UserValidator());
    }
    
    public JsonResult add(@Valid @RequestBody User user, Errors errors) {
        if (errors.hasErrors()) {
            //
        }
        //balabala
    }
}

just search for the specific usage

Menu