springMVC 全局异常处理

spring3.0注解很方便强大,所以更多的开发者都倾向于用注解来代替原来繁琐的配置,而对于异常也有相应的注解,我个人并不觉得在配置文件中配置全局异常很麻烦,如果整个项目都用了注解,而你再用配置就显得不伦不类,所以就用一个简单的方法来代替。写一个公共的controller,用@ExceptionHandler来拦截异常,然后此controller被其他controller继承,这样就用很少的代码解决异常拦截的问题,公共controller代码如下:

  1. @Controller  
  2. public class ExceptionHandlerController {  
  3.     @ExceptionHandler(RuntimeException.class)  
  4.     public String operateExp(RuntimeException ex,HttpServletRequest request){  
  5.         System.out.println("this is for test");  
  6.         //mod.addAttribute("err", ex.getMessage()); //ExceptionHandler处理异常时,Model,是不能用的,否则会不起作用,这里用了HttpServletRequest  
  7.         request.setAttribute("err", ex.getMessage());  
  8.         return "public/error";  
  9.     }  
原文地址:https://www.cnblogs.com/sddychj/p/6132766.html