模拟后台出现服务器异常
@GetMapping
public ResultResp list(@RequestParam(required = false) String name){
System.out.println(1/0);
List<Item> ret = service.lists(name);
return ResultResp.success(ret==null?Code.PAGE_FAIL:Code.PAGE_OK,ret);
}
出现如下错误

框架可能报错
持久层代码报错
业务层业务代码报错
控制层业务代码报错
注意:这些异常不能避免的,此时应该把所有的异常在表现层进行统一的处理(aop)
解决方案
@RestControllerAdvice
public class ExceptionHandlerController {
@ExceptionHandler(ArithmeticException.class)
public ResultResp handlerException(){
System.out.println("出现异常了");
return new ResultResp(500,null,"服务繁忙,请稍后再试");
}
}
使用来做控制器增强操作
| 名称 | @RestControllerAdvice |
|---|---|
| 位置 | Rest 风格增强类上 |
| 作用 | 给控制器做增强操作 |
| 使用 | 类上面 |
异常处理器
| 名称 | @ExceptionHandler |
|---|---|
| 位置 | 方法上 |
| 属性 | 具体的异常类型 |
| 作用 | 处理具体异常的,设定具体异常类型,出现异常后,终止controller中方法的执行,转入当前方法执行 |
业务异常
@Data
public class BusinessException extends RuntimeException{
private Integer code;
}
持久层异常
@Data
public class DaoException extends RuntimeException{
private Integer code;
}
系统异常
@Data
public class SystemException extends RuntimeException{
private Integer code;
}
其它异常
@Data
public class OtherException extends RuntimeException{
private Integer code;
}
定义code
public class Code {
/**
* 定义好协议之后,前端和后端统一按照协议执行
*/
public static final Integer SAVE_OK = 20000;
public static final Integer SAVE_FAIL = 20001;
public static final Integer UPDATE_OK = 20010;
public static final Integer UPDATE_FAIL = 20011;
public static final Integer DELETE_OK = 20020;
public static final Integer DELETE_FAIL = 20021;
public static final Integer GET_OK = 20030;
public static final Integer GET_FAIL = 20031;
public static final Integer PAGE_OK = 20040;
public static final Integer PAGE_FAIL = 20041;
public static final Integer BUSINESS_ERR = 50001;
public static final Integer SYSTEM_ERR = 50002;
public static final Integer DAO_ERR = 50003;
public static final Integer OTHER_ERR = 50005;
}
统一异常处理
@RestControllerAdvice
public class ExceptionHandlerController {
//业务异常的例子:账户名和密码错误
@ExceptionHandler(BusinessException.class)
public ResultResp handlerBusinessException(BusinessException e){
return new ResultResp(e.getCode(),null,e.getMessage());
}
//需要发送短信提醒运维人员
@ExceptionHandler(SystemException.class)
public ResultResp handlerSystemException(SystemException e){
//发送短信提醒业务人员的操作
//日志打印
return new ResultResp(e.getCode(),null,e.getMessage());
}
@ExceptionHandler(OtherException.class)
public ResultResp handlerException(OtherException e){
return new ResultResp(e.getCode(),null,e.getMessage());
}
}
控制层方法
@GetMapping
public ResultResp list(@RequestParam(required = false) String name) {
if (name == null || name.equals(""))
throw new BusinessException(Code.BUSINESS_ERR,"传参不正常请重试");
List<Item> ret = null;
try {
ret = service.lists(name);
} catch (Exception e) {
throw new SystemException(Code.SYSTEM_ERR,"系统繁忙,请稍后再试");
}
return ResultResp.success(ret == null ? Code.PAGE_FAIL : Code.PAGE_OK, ret);
}