全局異常處理器

輸入圖片說明

輸入圖片說明

輸入圖片說明

自定義異常類:java

package com.shi.ssm.exception;

/*
 * 自定義異常類
 */
public class CustomException extends Exception{
	private static final long serialVersionUID = 1L;
	private String message;
	public CustomException(String message){
		this.message=message;
	}
	public CustomException(){
		
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
}

輸入圖片說明

package com.shi.ssm.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/*
 * 全局異常處理器
 * ex 就是系統拋出的異常
 */
public class CustomExceptionRersolver implements HandlerExceptionResolver{

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		//handler就是處理器適配器要執行的handler對象(只有method)
		 
		String message=null;
		//解析出異常類型。
		//若是是系統自定義的異常:直接取出異常信息,在錯誤頁面展現
		/*if(ex instanceof CustomException){
			message=((CustomException)ex).getMessage();			
		}else{
			//若是不是系統自定義的異常,運行時異常,構造一個自定義的異常類型,(信息爲「未知異常」)
			message="未知錯誤";
		}*/
		//上邊代碼改成
		CustomException customException=null;
		if(ex instanceof CustomException){
			customException=(CustomException)ex;
		}else{
			customException=new CustomException("未知錯誤");
		}
		//錯誤信息封裝到頁面
		ModelAndView mv=new ModelAndView();
		mv.addObject("message", customException.getMessage());
		mv.setViewName("/WEB-INF/error.jsp");
		return mv;
	}
	
}

輸入圖片說明

<!-- 配置一個全局異常信息處理器 -->
	<bean class="com.shi.ssm.exception.CustomExceptionRersolver"></bean>
相關文章
相關標籤/搜索