在SpringMVC中提供了一种优雅的方式捕获Handler方法抛出的异常。接下来就看看是如何实现的。
方式一:在controller类型定义一个方法处理异常
- 在controller中定义一个方法,在方法上增加
@ExceptionHandler(ArithmeticException.class)
可以捕获具体的异常或者指定异常的子类异常
@ExceptionHandler(ArithmeticException.class)
public void handleException(ArithmeticException arithmeticException, HttpServletResponse response) throws IOException {
response.getWriter().write(arithmeticException.getMessage());
}
捕获异常后的处理方式:
- 将异常返回到界面
- 直接返回到一个error界面
- 或者直接输出到response中
这种方式只针对当前controller有效,其他controller中的异常是无法捕获的。
方式二:定义一个共同异常处理类
@ControllerAdvice
public class ExceptionHandlerClass {
@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception exception){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg",exception.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
这个异常处理类必须是能被Spring容器扫描到的,注册到Spring容器中,才能起作用。
扫描组件配置:
<context:component-scan base-package="com.fuyf.stu.exception.handler"></context:component-scan>
这样就可以将所有的异常处理放在一个类中,进行统一管理了。