全局异常
@Data
@AllArgsConstructor
public class GlobalException extends RuntimeException{
private RespBeanEnum respBeanEnum;
}
注:此处使用@AllArgsConstructor初始化一个全参构造器
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public RespBean ExceptionHandler(Exception e) {
if (e instanceof GlobalException) {
GlobalException ex = (GlobalException) e;
return RespBean.error(ex.getRespBeanEnum());
} else if (e instanceof BindException) {
BindException ex = (BindException) e;
RespBean respBean = RespBean.error(RespBeanEnum.BING_ERROR);
respBean.setMessage("参数校验异常~:" + ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return respBean;
}
return RespBean.error(RespBeanEnum.ERROR);
}
}
拓展:上面的绑定异常可以在Vo实体中应用,当下面的属性的校验未通过时,会抛出绑定异常
@Data
public class LoginVo {
@NotNull
@IsMobile
private String mobile;
@NotNull
@Length(min = 32)
private String password;
}
User user = userMapper.selectById(mobile);
if (null == user) {
throw new GlobalException(RespBeanEnum.LOGIN_ERROR)
}