java之异常统一处理

时间:2023-01-05 09:42:52

spring-mvc.xml

 <!-- aop -->
<aop:aspectj-autoproxy/>
<beans:bean id="controllerAop" class="com.financial.server.aop.ControllerAOP"/>
<aop:config><!-- 环绕通知 统一捕捉controller方法抛出的异常并进行处理 -->
<aop:aspect id="myAop" ref="controllerAop">
<aop:pointcut expression="@annotation (org.springframework.web.bind.annotation.RequestMapping)" id="target"/>
<aop:around method="handlerControllerMethod" pointcut-ref="target"/>
</aop:aspect>
</aop:config>

controller层拦截处理异常

 package com.financial.server.aop;

 import java.lang.reflect.Method;
import java.util.Map; import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.servlet.ModelAndView; import com.financial.server.util.ResultBean; public class ControllerAOP { private static final Logger logger = Logger.getLogger(ControllerAOP.class); public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
long startTime = System.currentTimeMillis();
Object result;
Signature s = pjp.getSignature();
MethodSignature ms = (MethodSignature) s;
Method m = ms.getMethod();
try {
result = pjp.proceed();
logger.info (pjp.getSignature() + "接口用时:" + (System.currentTimeMillis() - startTime) + "毫秒");
} catch (Throwable e) {
result = handlerException(pjp, e, m.getReturnType().getSimpleName());
}
return result;
} private Object handlerException(ProceedingJoinPoint pjp, Throwable e, String returnName) {
e.printStackTrace();
if ("ModelAndView".equals(returnName)) {
ModelAndView mv = new ModelAndView("error");
return mv;
} else if ("ResultBean".equals(returnName)) {
ResultBean result = new ResultBean();
logger.error(pjp.getSignature() + " error ", e);
result.setMsg("服务器异常!请稍后重试!");
result.setCode(result.FAILTRUE);
// 异常这里可以做其他操作,如通知邮件,单独写到某个文件等等。
logger.info(e, e);
logger.error(e.getMessage(), e);
return result;
} else if ("String".equals(returnName)) {
return "error1";
} else {
return "error";
} }
}

测试方法

 @RequestMapping("/aa")
public ModelAndView aa() throws Exception{
throw new Exception("aa");
} @RequestMapping("/bb")
public String bb() throws Exception{
throw new Exception("bb");
} @RequestMapping("/cc")
@ResponseBody
public ResultBean cc() throws Exception{
throw new Exception("aa");
}