1. 程式人生 > >java web 之路:springmvc全域性異常處理

java web 之路:springmvc全域性異常處理

通常出現異常的處理方法:dao拋給server、server拋給controller、controller拋給前端控制,前端控制器呼叫全域性異常處理器。

全域性異常處理器處理思路:

解析出異常型別

       如果是已知的異常,直接取出異常資訊,在錯誤頁頁面展示

       如果是未已的異常,構造一個自定義異常型別(未知錯誤)

       新建全域性異常處理類

新建異常處理類,繼承Excepiton

package cn.itcast.ssm.exception;

public class CustomException extends Exception{
	private String message=null;
	
	public CustomException(String message) {
		// TODO Auto-generated constructor stub
		super(message);
		this.message=message;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
}

新建全域性異常處理類,繼承HandlerExceptionResolver

package cn.itcast.ssm.exception;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class CustomExceptionResolver implements HandlerExceptionResolver{
	
	CustomException customexception = null;
	
	@Override
	public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object handler,
			Exception ex) {
		// TODO Auto-generated method stub


		if(ex instanceof CustomException) {
			customexception = (CustomException)ex;
		
		}else {
			customexception = new CustomException("未知錯誤");
		}
		
		String message = customexception.getMessage();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("message", message);
		modelAndView.setViewName("error");
		
		
		return modelAndView;
	}
	
	
	
	

}

在springmvc.xml中配置全域性異常處理類,只要是繼承了handlerException的就是全域性異常處理類。

<bean class="cn.itcast.ssm.exception.CustomExceptionResolver"/>

通常如果是業務類的異常處理,在servce中處理

不是業務類的異常處理,在controller中處理