springmvc和mybatis整合的异常处理

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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.错误信息的展示

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航