自定义一个异常类
//自定义的异常类型,实际开发中可能要定义多种异常类型
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;
}
}
定义一个异常处理类,要实现HandlerExceptionResolver 接口
public class CustomExceptionResolver implements HandlerExceptionResolver {
//前端控制器DispatcherServlet在进行HandlerMapping、调用HandlerAdapter执行Handler过程中,如果遇到异常就会执行此方法
//handler最终要执行的Handler,它的真实身份是HandlerMethod
//Exception ex就是接收到异常信息
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
//首先在控制台输出异常信息
ex.printStackTrace();
//统一异常处理代码
//针对系统自定义的CustomException异常,就可以直接从异常类中获取异常信息,将异常处理在错误页面展示
//异常信息
String message = null;
CustomException customException = null;
//如果ex是自定义的异常,直接取出异常信息
if(ex instanceof CustomException){
customException = (CustomException)ex;
}else{
//针对非CustomException异常,对这类重新构造成一个CustomException,异常信息为“未知错误”
customException = new CustomException("未知错误");
}
//错误 信息
message = customException.getMessage();
request.setAttribute("message", message);
try {
//转向到错误 页面
request.getRequestDispatcher("a.jsp").forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView();
}
在springmvc.xml中配置
<!-- 定义统一异常处理器 -->
<bean class="cn.itcast.springmvc.exception.CustomExceptionResolver"></bean>
@RequestMapping("/exceptionTest")
public void requestKeyValue(HttpServletRequest request, HttpServletResponse response)throws Exception{
Person p=null;
if(p==null){
throw new CustomException("Person类为null");
}
}
<p>${message}</p>
一般要求dao,service,controller遇到异常全部向上抛出,前端控制器DispatcherServlet统一捕获异常,然后调用异常处理器(全系统只有一个)处理,异常处理器需要实现HandlerExceptionResolver接口。