@Data @NoArgsConstructor @AllArgsConstructor public class GlobalException extends RuntimeException { //这个是留给后面用的 什么异常自己注入 private RespBeanEnum respBeanEnum; }
@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.BIND_ERROR); respBean.setMessage("参数校验异常:" + ex.getBindingResult().getAllErrors().get(0).getDefaultMessage()); return respBean; } return RespBean.error(RespBeanEnum.ERROR); } }
这里的场景是 因为手机号码校验不成功
所以是bindexception 会获得那个异常