spring mvc 和mybatis整合 的異常處理,mvcmybatis

來源:互聯網
上載者:User

spring mvc 和mybatis整合 的異常處理,mvcmybatis

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.錯誤資訊的展示

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.