程序开发过程中不可避免的会遇到异常现象
出现异常现象的常见位置与常见诱因如下:
所有的异常均抛出到表现层进行处理
表现层处理异常,每个方法中单独书写,代码书写量巨大且意义不强,使用AOP思想统一处理
编写异常处理器、集中的、统一的处理项目中出现的异常
@RestControllerAdvice //用于标识当前类为REST风格对应的异常处理器 public class ProjectExceptionAdvice { //统一处理所有的Exception异常 @ExceptionHandler(Exception.class) public Result doOtherException(Exception ex){ return new Result(500,null,"系统异常"); } }
使用异常处理器之后的效果
@RestControllerAdvice注解介绍
@ExceptionHandler注解介绍
项目异常分类
业务异常(BusinessException)
系统异常(SystemException)
其他异常(Exception)
项目异常处理方案
系统异常(SystemException)
其他异常(Exception)
自定义项目系统级异常
//自定义异常处理器,用于封装异常信息,对异常进行分类 public class SystemException extends RuntimeException{ private Integer code; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public SystemException(Integer code, String message) { super(message); this.code = code; } public SystemException(Integer code, String message, Throwable cause) { super(message, cause); this.code = code; } }
自定义项目业务级异常
//自定义异常处理器,用于封装异常信息,对异常进行分类 public class BusinessException extends RuntimeException{ private Integer code; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public BusinessException(Integer code, String message) { super(message); this.code = code; } public BusinessException(Integer code,String message,Throwable cause) { super(message, cause); this.code = code; } }
public class Code { //状态码 public static final Integer SAVE_OK = 20011; public static final Integer DELETE_OK = 20021; public static final Integer UPDATE_OK = 20031; public static final Integer GET_OK = 20041; public static final Integer SAVE_ERR = 20010; public static final Integer DELETE_ERR = 20020; public static final Integer UPDATE_ERR = 20030; public static final Integer GET_ERR = 20040; public static final Integer SYSTEM_ERR = 50001; public static final Integer SYSTEM_TIMEOUT_ERR = 50002; public static final Integer SYSTEM_UNKNOW_ERR = 59999; public static final Integer BUSINESS_ERR = 60002; }
@Service public class BookServiceImpl implements BookService { @Autowired private BookDao bookDao; //在getById演示触发异常,其他方法省略没有写进来 public Book getById(Integer id) { //模拟业务异常,包装成自定义异常 if(id <0){ throw new BusinessException(Code.BUSINESS_ERR,"项目业务级异常!"); } } }