<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
下面是controller层运行异常后的切面处理
import co.yiiu.core.bean.Result;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created date on 2018/11/26
* Author Zy
*/
@Slf4j
@Aspect
@Component
public class WebExceptionAspect{
private Exception e;
//凡是注解了RequestMapping的方法都被拦截
@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
private void webPointcut() {
}
@Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
private void postPointcut() {
}
@Pointcut("execution(* co.yiiu.web.bountyHunter..*.*(..))")
private void bountyHunterPointcut() {
}
@Before("bountyHunterPointcut()")
public void beforeLog(JoinPoint joinPoint){
log.info("我是前置通知"+joinPoint.getSignature().getName());
}
/**
* 拦截web层异常,记录异常日志,并返回友好信息到前端 目前只拦截Exception,是否要拦截Error需再做考虑
*
* @param e
* 异常对象
*/
@AfterThrowing(pointcut = "bountyHunterPointcut()", throwing = "e")
public void handleThrowing(JoinPoint joinPoint,Exception e) {
this.e = e;
//e.printStackTrace();
log.error("发现异常!" + e.getMessage());
//log.error(JSON.toJSONString(e.getStackTrace()));
//这里输入友好性信息
writeContent("出现异常" + e.getMessage());
}
/**
* 将内容输出到浏览器
*
* @param content
* 输出内容
*/
private void writeContent(String content) {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getResponse();
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "text/json;charset=UTF-8");
response.setHeader("icop-content-type", "exception");
PrintWriter writer = null;
JsonGenerator jsonGenerator = null;
try {
writer = response.getWriter();
jsonGenerator = (new ObjectMapper()).getFactory().createGenerator(writer);
jsonGenerator.writeObject(Result.error(500,content));
} catch (IOException e1) {
e1.printStackTrace();
}finally {
writer.flush();
writer.close();
}
}
}
需要注意的一点是,该类必须注册进spring容器内。有很多种方式,这里就不说了!