spring mvc 和mybatis整合 的异常处理

1.自定义异常信息类 通过构造函数来实现异常信息的接收

public class CustomException extends Exception {

//异常信息
private String message;

public CustomException (String message){
super(message);
this.message = message;
}
public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}

2.通过实现HandlerExceptionResolver的接口来实现异常处理  流程:先是解析异常,再判断是否是系统自定义异常,如果是就直接抛出异常,如果不是自定义异常就直接构造一个自定义的异常类型(信息为“未知错误,请与管理员联系!”)

//不是自定义饿异常多半是运行异常,尽量在测试的时候就解决掉

public class CustomExceptionResolver implements HandlerExceptionResolver {

@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {


CustomException customException=null;
if(ex instanceof CustomException ){
customException = (CustomException)ex;
}else{
customException = new CustomException("未知错误,请与管理员联系!");
}
//获取错误信息
String message = customException.getMessage();
System.out.println("异常信息:"+message);
//创建ModelAndView对象
ModelAndView modelAndView = new ModelAndView();
//把错误信息填充到request域中
modelAndView.addObject("message", message);
//传入到页面
modelAndView.setViewName("error");
return modelAndView;
}

}

3.在spring 的xml文件中配置 class 是CustomExceptionResolver的路径

<!-- 异常处理器 -->
<bean class="com.menglin.ssm.exception.CustomExceptionResolver"></bean>

 4.开始测试  (需求:当在查询的时候如果信息不存在的时候就抛出异常 )

/**
* 根据id来查询
*/
@Override
public ItemsCustom findItemsCustomById(Integer id) throws Exception {
ItemsCustom itemsCustom = null;
Items items = itemsMapper.selectByPrimaryKey(id);
if(items==null){

throw new CustomException("商品信息不存在!");
}else{
itemsCustom = new ItemsCustom();
BeanUtils.copyProperties(items, itemsCustom);
}
return itemsCustom;

}

5.错误信息的展示

spring mvc 和mybatis整合 的异常处理

spring mvc 和mybatis整合 的异常处理spring mvc 和mybatis整合 的异常处理