java之异常统一处理
程序员文章站
2022-07-02 14:03:58
spring-mvc.xml 1 2 3 4
View Code
View Code
View Code
spring-mvc.xml
1 <!-- aop --> 2 <aop:aspectj-autoproxy/> 3 <beans:bean id="controllerAop" class="com.financial.server.aop.ControllerAOP"/> 4 <aop:config><!-- 环绕通知 统一捕捉controller方法抛出的异常并进行处理 --> 5 <aop:aspect id="myAop" ref="controllerAop"> 6 <aop:pointcut expression="@annotation (org.springframework.web.bind.annotation.RequestMapping)" id="target"/> 7 <aop:around method="handlerControllerMethod" pointcut-ref="target"/> 8 </aop:aspect> 9 </aop:config>
controller层拦截处理异常
1 package com.financial.server.aop; 2 3 import java.lang.reflect.Method; 4 import java.util.Map; 5 6 import org.apache.log4j.Logger; 7 import org.aspectj.lang.ProceedingJoinPoint; 8 import org.aspectj.lang.Signature; 9 import org.aspectj.lang.reflect.MethodSignature; 10 import org.springframework.web.servlet.ModelAndView; 11 12 import com.financial.server.util.ResultBean; 13 14 public class ControllerAOP { 15 16 private static final Logger logger = Logger.getLogger(ControllerAOP.class); 17 18 public Object handlerControllerMethod(ProceedingJoinPoint pjp) { 19 long startTime = System.currentTimeMillis(); 20 Object result; 21 Signature s = pjp.getSignature(); 22 MethodSignature ms = (MethodSignature) s; 23 Method m = ms.getMethod(); 24 try { 25 result = pjp.proceed(); 26 logger.info 27 28 (pjp.getSignature() + "接口用时:" + (System.currentTimeMillis() - startTime) + "毫秒"); 29 } catch (Throwable e) { 30 result = handlerException(pjp, e, m.getReturnType().getSimpleName()); 31 } 32 return result; 33 } 34 35 private Object handlerException(ProceedingJoinPoint pjp, Throwable e, String returnName) { 36 e.printStackTrace(); 37 if ("ModelAndView".equals(returnName)) { 38 ModelAndView mv = new ModelAndView("error"); 39 return mv; 40 } else if ("ResultBean".equals(returnName)) { 41 ResultBean result = new ResultBean(); 42 logger.error(pjp.getSignature() + " error ", e); 43 result.setMsg("服务器异常!请稍后重试!"); 44 result.setCode(result.FAILTRUE); 45 // 异常这里可以做其他操作,如通知邮件,单独写到某个文件等等。 46 logger.info(e, e); 47 logger.error(e.getMessage(), e); 48 return result; 49 } else if ("String".equals(returnName)) { 50 return "error1"; 51 } else { 52 return "error"; 53 } 54 55 } 56 }
测试方法
1 @RequestMapping("/aa") 2 public ModelAndView aa() throws Exception{ 3 throw new Exception("aa"); 4 } 5 6 @RequestMapping("/bb") 7 public String bb() throws Exception{ 8 throw new Exception("bb"); 9 } 10 11 @RequestMapping("/cc") 12 @ResponseBody 13 public ResultBean cc() throws Exception{ 14 throw new Exception("aa"); 15 }
上一篇: AQS同步队列器之三:等待通知机制
下一篇: 我们还有梦