Spring Boot 2.X(十一):全局异常处理 (2)

@ControllerAdvice 还能结合 @ModelAttribute 、@InitBinder 注解一起使用,实现全局数据绑定和全局数据预处理等功能。

实现 HandlerExceptionResolver 接口 1.定义统一异常处理类 @Component public class GlobalHandlerExceptionResolver implements HandlerExceptionResolver { private Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { Exception e = new Exception(); //处理 UndeclaredThrowableException if (ex instanceof UndeclaredThrowableException) { e = (Exception) ((UndeclaredThrowableException) ex).getUndeclaredThrowable(); } else { e = ex; } e.printStackTrace(); //这里可以根据不同异常引起的类做不同处理方式 String exceptionName = ClassUtils.getShortName(e.getClass()); if(exceptionName.equals("ArrayIndexOutOfBoundsException")) { log.error("GlobalHandlerExceptionResolver resolveException ===>" + exceptionName); ModelAndView mav = new ModelAndView(); mav.addObject("stackTrace", e.getStackTrace()); mav.addObject("exceptionName", exceptionName); mav.addObject("errorMessage", e.getMessage()); mav.addObject("url", request.getRequestURL()); mav.setViewName("forward:/error/500"); return mav; } return null; } }

UndeclaredThrowableException 异常通常是在 RPC 接口调用场景或者使用 JDK 动态代理的场景时发生。如果不预先处理转换,测试捕获到的异常则为 UndeclaredThrowableException,而不是真实的异常对象。

2.异常信息展现 同上 3.测试异常类 @Controller public class TestController { @GetMapping("/test") public String test() { String[] ss = new String[] { "1", "2" }; System.out.print(ss[2]); return "hello"; } } 4.测试运行

测试前先把 @ControllerAdvice 注释了。
浏览器访问::8080/test

Spring Boot 2.X(十一):全局异常处理

示例代码

github

码云

非特殊说明,本文版权归 朝雾轻寒 所有,转载请注明出处.

原文标题:Spring Boot 2.X(十一):全局异常处理

原文地址:https://www.zwqh.top/article/info/20

如果文章对您有帮助,请扫码关注下我的公众号,文章持续更新中...

Spring Boot 2.X(十一):全局异常处理

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzfxgy.html