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

 

转载于:https://www.cnblogs.com/lemon863376328/p/5010049.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值