【SpringMvc异常处理,传智播客视频笔记】

异常处理的思路:

  

  

1. 创建一个异常类,这个类要继承Exception,用于封装异常信息

  

2.创建全局异常处理器(用于捕获系统异常)

  

CustomExceptionResolver .java:
package cn.itcast.ssm.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframeword.web.servlet.ModelAndView;

// 全局异常处理器
public class CustomExceptionResolver implements HandlerExceptionResolver {
	public ModelAndView resolveException(HttpServletRequest request,
		HttpServletResponse response, Object handler, Exception ex) {
		// handler就是处理器适配器要执行的Handler对象(只有method)
		// ex就是被系统(前端控制器)捕获到的异常类对象
		
		// 解析出异常类型
		CustomException customException = null;
		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;
	}
}

3.创建显示错误信息的页面

error.jsp

  

4. 在springmvc.xml中配置全局异常处理器

  

 5.异常测试

  

   

 

posted @ 2017-06-18 14:06  半生戎马,共话桑麻、  阅读(174)  评论(0)    收藏  举报
levels of contents