自定义异常类:
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>