SpringMVC提供了统一的异常处理
这里只提供SpringMVC全局异常处理的简单应用,并不包含其原理,文中如有不妥,还请前辈们不吝赐教
SpringMVC提供了统一的异常处理,接口HandlerExceptionResolver,自定义类实现HandlerExceptionResolver接口,重写resolveException方法。使用此方法可以在Controller层不抛出异常的情况,自动捕获异常,进行处理,相关步骤如下:
CustomExceptionResolver
//全局异常处理器
public class CustomExceptionResolver implements HandlerExceptionResolver {
//系统抛出的异常
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
//handler就是处理器适配器要执行的Handler对象(只有method)
//解析出异常类型。
System.out.println("异常");
CustomException customException = null;
//如果该 异常类型是系统 自定义的异常,直接取出异常信息,在错误页面展示。
if (e instanceof CustomException){
customException = (CustomException) e;
}else{
//如果该 异常类型不是系统 自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)。
customException = new CustomException("发生了一个未知的错误,请重试");
}
//错误信息
String message = customException.getMessage();
//将错误信息传到页面,并且指向错误页面
return new ModelAndView("redirect:/Index.html","message",message);
}
}
CustomException
//创建自定义异常
public class CustomException extends Exception {
//异常信息
private String message;
public CustomException(String message) {
super(message);
this.message = message;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
SpringMVC的配置文件中注入
<!--自定义异常-->
<bean class="com.hqyj.IoT.exception.CustomExceptionResolver"/>
如果有兴趣,可以去看看,Spring中HandlerExceptionResolver部分的源码,想要了解其原理,还是看源码比较好。