1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2、参数或参数对象添加校验注解,详细校验注解自行百度/Google
public class FrmDeptParam implements Serializable {
private Integer id;
@NotBlank(message = "部门名称不能为空")
private String name;
@Size(max = 200,message = "备注说明字数不能超过200字")
private String remark;
}
3、controller注入参数时,添加@valid注解
@PostMapping("/saveDept")
public ResultResponse<String> saveDept(@Valid @RequestBody FrmDeptParam param){
return ResultResponse.success();
}
4、新增全局异常处理类,大功告成
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value=Exception.class)
public ResultResponse<String> exceptionHandler(HttpServletRequest request, Exception e){
logger.error(e.getMessage(),e);
if(e instanceof GlobalException) {
GlobalException ex = (GlobalException)e;
return ResultResponse.error(ex.getCm());
}
//参数校验异常处理
else if(e instanceof MethodArgumentNotValidException){
MethodArgumentNotValidException mne = (MethodArgumentNotValidException)e;
ObjectError error = mne.getBindingResult().getAllErrors().get(0);
return ResultResponse.error(CodeMsg.BIND_ERROR.fillArgs(error.getDefaultMessage()));
}
else {
return ResultResponse.error(CodeMsg.SERVER_ERROR);
}
}
}