国产探花免费观看_亚洲丰满少妇自慰呻吟_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.錯誤信息的展示

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 资兴市| 临邑县| 金乡县| 吉木萨尔县| 乌恰县| 那坡县| 镶黄旗| 凭祥市| 龙口市| 小金县| 南京市| 西充县| 辉南县| 白玉县| 临邑县| 竹溪县| 永吉县| 澎湖县| 剑河县| 保康县| 云阳县| 寿阳县| 吴忠市| 仙居县| 晋州市| 呼和浩特市| 乌拉特后旗| 尼勒克县| 陈巴尔虎旗| 柘城县| 皋兰县| 库车县| 岳普湖县| 肇东市| 虎林市| 张家口市| 葫芦岛市| 宁远县| 高要市| 涿鹿县| 九寨沟县|