参数校验及统一异常捕获
参考地址:
一、参数校验分类
public class ArgumetValidate { /** * 限定保存必传字段 */ public interface Save{} /** *限定修改必传字段 */ public interface Update{} }
二、实体类注解
@NotNull(message="xx不能为空",groups = ArgumetValidate.Update.class)
private Long appId;
@NotBlank(message = "xx不能为空", groups = ArgumetValidate.Save.class)
private String appName;
三、web层相关注解
/** * 新增 * @param t * @return */ @PostMapping("insert") public String insert(@RequestBody @Validated(ArgumetValidate.Save.class) T t) { xxService.insert(t); return "ok"; } /** * 更新 * @param t * @return */ @PostMapping("update") public String update(@RequestBody @Validated(ArgumetValidate.Update.class) T t) { xxService.update(t); return "ok"; }
四、统一异常捕获
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ReturnData MethodArgumentNotValidException(MethodArgumentNotValidException e){ BindingResult bindingResult = e.getBindingResult(); StringBuilder sb = new StringBuilder("校验失败:"); for (FieldError fieldError : bindingResult.getFieldErrors()) { sb.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(", "); } return new ReturnData(SysCodeMsg.PARAM_IS_ERROR.getCode(),sb.toString()); } @ExceptionHandler({ConstraintViolationException.class}) public ReturnData handleConstraintViolationException(ConstraintViolationException e) { return new ReturnData(SysCodeMsg.PARAM_IS_ERROR.getCode(),e.getMessage()); } @ExceptionHandler(Exception.class) public ReturnData exception(Exception e){ // 根据不同错误返回不同的信息 String res; if (e instanceof SQLException) { // 非运行异常 res = "数据库异常:"; log.error("数据库异常:",e); } else if (e instanceof IOException) { res = "IO流异常"; log.error("IO流异常:",e); } else if (e instanceof RuntimeException) {// 运行异常 res = "运行时异常"; log.error("运行时异常:",e); } else {// 错误 res = "系统错误"; log.error("系统错误:",e); } Integer code = SysCodeMsg.SYS_ERROR.getCode(); //自定义异常 if (e.getClass().getName().startsWith("com.xx.xx.exceptions")) { res = e.getMessage(); code = SysCodeMsg.FAIL.getCode(); } return new ReturnData(code,res); }