@Async异步方法对异常的处理,从内层向外层抛出机制
@RequestMapping(value = "/test", method = RequestMethod.GET) public String test(){ try { System.out.println("主方法执行开始>>>>>>>>>>>>>>>"); //myService依赖注入进来 myService.test(); System.out.println("主方法执行完毕>>>>>>>>>>>>>>>"); }catch (Exception e) { System.out.println("主方法异常>>>>>>>>>>>>>>>"); e.printStackTrace(); return "fail"; } return "success"; } //MyService.java public void test() throws Exception{ System.out.println("开始执行test"); try{ testAsync(); }catch (Exception e) { System.out.println("test service异常>>>>>>"); e.printStackTrace(); throw e; } System.out.println("结束执行test"); } @Async public void testAsync() throws Exception{ System.out.println("开始执行testAsync"); try{ int i = 1/0; }catch (Exception e) { System.out.println("testAsync service异常>>>>>>"); e.printStackTrace(); //关键,在异步方法中也可以抛出异常 // throw e; } System.out.println("结束执行testAsync"); }
DEMO测试结论:
/*
*CASE1:在testAsync方法中保留:throw e;
* http://localhost:8080/proj/test
* 页面输出:fail
* 主方法执行开始>>>>>>>>>>>>>>>
* 开始执行test
* 开始执行testAsync
* testAsync service异常>>>>>>
* test service异常>>>>>>
* 主方法异常>>>>>>>>>>>>>>>
*
*
*CASE2:在testAsync方法中注释:throw e;
* testAsync方法注释之后,运行的效果:
* http://localhost:8080/proj/test
* 页面输出:success
* // throw e;
*
* 主方法执行开始>>>>>>>>>>>>>>>
* 开始执行test
* 开始执行testAsync
* testAsync service异常>>>>>>
* 结束执行testAsync
* 结束执行test
* 主方法执行完毕>>>>>>>>>>>>>>>
*/
标签:testAsync,异步,System,内层,println,test,Async,执行,out From: https://www.cnblogs.com/oktokeep/p/16596469.html