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