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.錯誤信息的展示
新聞熱點
疑難解答