星空网 > 软件开发 > Java

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 的

<!-- 异常处理器 -->
<bean ></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整合 的异常处理

 




原标题:spring mvc 和mybatis整合 的异常处理

关键词:Spring

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

深环海物流:https://www.goluckyvip.com/news/1826.html
顺通发物流:https://www.goluckyvip.com/news/1827.html
紧急通知!菲律宾海关出新规!违者将面临罚金,影响清关!:https://www.goluckyvip.com/news/1828.html
印尼清关红灯期要来了!注意你的货物!:https://www.goluckyvip.com/news/1829.html
Wish发布产品价格限制政策 / Lazada强推国货出海:https://www.goluckyvip.com/news/183.html
东南亚跨境电商shopee选品指南---新手必读!:https://www.goluckyvip.com/news/1830.html
有威海直到崂山风景区车吗 威海到青岛崂山怎么走最快:https://www.vstour.cn/a/404250.html
特点有哪些?债券的定义?:https://www.vstour.cn/a/404251.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流