默认的异常处理机制是向上抛出,最终将异常结果抛在web页面,这样对用户来说很不友好,所以可以通过自定义异常的方式来解决这个问题。
第一步:自定义一个异常类:
//自定义异常类
public class SysException extends Exception {
private String message;
public SysException(String message) {
this.message = message;
}
public SysException() {
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
//写一个异常处理器 继承HandlerExceptionResolver接口
public class ExceptionHandler implements HandlerExceptionResolver {
/**
* @param httpServletRequest 请求
* @param httpServletResponse 响应
* @param o
* @param e 传过来的异常
* @return
*/
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
SysException exception = null;
ModelAndView mv = new ModelAndView();
if (e instanceof SysException) {
exception = (SysException) e;
} else {
exception = new SysException("系统正在维护");
}
mv.addObject("msg",exception.getMessage());
mv.setViewName("error");
return mv;
}
}
配置异常处理器
<!--配置异常处理器-->
<bean id="exceptionHandler" class="com.mayao.Exception.ExceptionHandler"></bean>