写程序的时候一般都会通过try...catch...finally对异常进行处理,但是我们真的能在写程序的时候处理掉所有可能发生的异常吗? 以及发生异常的时候执行什么逻辑,返回什么提示信息,跳转到什么页面,这些都是要考虑到的。
前面章节介绍了基于@ControllerAdvice(加强的控制器)的异常处理
请参考 http://gsshijun.iteye.com/admin/blogs/2321980
下面介绍一些基于spring aop进行异常处理的方式:
1、添加pom
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2、参考示例
/** * 异常拦截处理 * @author ThinkPad * */ @Aspect @Component public class ExceptionInterceptor { //拦截com.sjz.cnmtc.web.main包及其子包下面的所有类下的所有方法 @Pointcut("execution(* com.sjz.cnmtc.web.main..*.*(..))") private void myPointcut() { } @AfterThrowing(throwing="ex" , pointcut="myPointcut()") public void doRecoveryActions(Throwable ex){ System.out.println("目标方法中抛出的异常:" + ex); writeContent("目标方法中抛出的异常"); } /** * 将内容输出到浏览器 * * @param content 输出内容 */ private void writeContent(String content) { HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); // response.reset(); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Type", "text/plain;charset=UTF-8"); response.setHeader("icop-content-type", "exception"); PrintWriter writer = null; try { writer = response.getWriter(); } catch (IOException e) { e.printStackTrace(); } writer.print(content); writer.flush(); writer.close(); } }