能够掌握SSM整合的流程
能够编写SSM整合功能模块类
能够使用Result统一表现层响应结果
能够编写异常处理器进行项目异常
能够完成SSM整合前端页面发送请求实现增删改查操作
能够编写拦截器并配置拦截器
请说出项目当前异常的分类以及对应类型异常该如何处理?
业务异常(BusinessException)
系统异常(SystemException)
其他异常(Exception)
业务异常(BusinessException)
系统异常(SystemException)
其他异常(Exception)
xxxxxxxxxx
//自定义异常处理器,用于封装异常信息,对异常进行分类
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;
}
}
xxxxxxxxxx
//自定义异常处理器,用于封装异常信息,对异常进行分类
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;
}
}
xxxxxxxxxx
public class Code {
//之前其他状态码省略没写,以下是新补充的状态码,可以根据需要自己补充
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;
}
xxxxxxxxxx
public class BookServiceImpl implements BookService {
private BookDao bookDao;
//在getById演示触发异常,其他方法省略没有写进来
public Book getById(Integer id) {
//模拟业务异常,包装成自定义异常
if(id <0){
throw new BusinessException(Code.BUSINESS_ERR,"请不要使用你的技术挑战我的耐性!");
}
}
}
xxxxxxxxxx
//用于标识当前类为REST风格对应的异常处理器
public class ProjectExceptionAdvice {
//@ExceptionHandler用于设置当前处理器类对应的异常类型
SystemException.class) (
public Result doSystemException(SystemException ex){
//记录日志
//发送消息给运维
//发送邮件给开发人员,ex对象发送给开发人员
return new Result(ex.getCode(),null,ex.getMessage());
}
BusinessException.class) (
public Result doBusinessException(BusinessException ex){
return new Result(ex.getCode(),null,ex.getMessage());
}
//除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
Exception.class) (
public Result doOtherException(Exception ex){
//记录日志
//发送消息给运维
//发送邮件给开发人员,ex对象发送给开发人员
return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
}
}
测试:在postman中发送请求访问getById方法,传递参数-1,得到以下结果: