今天在做项目的时候突然发现异常处理还有所欠缺,所有打算好好的加强一下异常的处理,顺便好好巩固以前学习的知识和增加新的知识。
首先看一看通过实现Spring的异常处理接口
- 实现Spring接口-HandlerExceptionResolver
public class ExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
// TODO Auto-generated method stub
return null;
}
}
这个接口只定义了一个返还值为ModelAndView的接口,看源码和注释就很容易知道它的用法了。
注释中说明:Implementors are typically registered as beans in the application context.是一个需要配置成一个Bean的形式。
<!-- 异常处理 -->
<bean class="com.***.Exception.ExceptionResolver" />
以下便是一个小小的例子:
public class ExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
if (ex instanceof NullArgumentException) {
HandlerMethod method=(HandlerMethod) handler;
System.out.println(method.getMethod());
System.out.println("异常拦截成功!");
return new ModelAndView("redirect:/Test.jsp");
}
return null;
}
}
写一个TestController模拟抛出异常
@RequestMapping("/Exception.do")
public String ExceptionMethod() throws Exception {
throw new NullArgumentException("模拟异常抛出");
}
测试结果:
页面也跳转了:
同样也可以通过继承AbstractHandlerExceptionResolver类:
public class ExceptionResolver extends AbstractHandlerExceptionResolver{
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
// TODO Auto-generated method stub
return null;
}
}
注意:上面这种方式只能捕获抛出的异常,如果在Controller内被catch下的异常是不会被处理的!
2.通过使用@ControllerAdvice注解的方式实现异常的处理
@ControllerAdvice
public class WebExceptionHandler {
@ExceptionHandler(NullPointerException.class)
public ModelAndView nullPointException() {
System.out.println("空指针异常!");
return new ModelAndView("Test");
}
}