国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

springmvc和mybatis整合的異常處理

2019-11-14 14:56:44
字體:
來源:轉載
供稿:網友

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.錯誤信息的展示

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 昭通市| 长岭县| 铜山县| 翁牛特旗| 长垣县| 项城市| 通渭县| 衢州市| 玛曲县| 自治县| 东宁县| 平度市| 林芝县| 油尖旺区| 开封市| 乐陵市| 安丘市| 上杭县| 西乌珠穆沁旗| 保德县| 云阳县| 林州市| 汽车| 安远县| 九龙县| 鄂温| 平江县| 霍城县| 安化县| 青州市| 兰州市| 乐都县| 庆安县| 白山市| 抚宁县| 常德市| 浦县| 丹凤县| 化隆| 卓资县| 渝北区|