
spring-aop maven依赖+捕获controller运行异常后的切面处理
发布日期:2021-05-15 08:19:44
浏览次数:17
分类:精选文章
本文共 2500 字,大约阅读时间需要 8 分钟。
org.aspectj aspectjrt 1.9.2 org.aspectj aspectjweaver 1.9.2 Web层运行异常后的切面处理实现
import co.yiiu.core.bean.Result;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.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;/** * 创建日期:2018/11/26 * 作者:Zy */@Slf4j@Component@Aspectpublic class WebExceptionAspect { private Exception e; @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()); } @AfterThrowing(pointcut = "bountyHunterPointcut()", throwing = "e") public void handleThrowing(JoinPoint joinPoint, Exception e) { this.e = e; //e.printStackTrace(); log.error("发现异常!" + e.getMessage()); writeContent("出现异常" + e.getMessage()); } 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容器中,具体方式可依据项目实际需求选择。
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2025年04月20日 02时01分55秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
修改layui的后台模板的左侧导航栏可以伸缩
2019-03-12
Mybatis Generator最完整配置详解
2019-03-12
报错:For input string
2019-03-12
ThreadLocal源码分析解密
2019-03-12
【Java并发编程】并发编程大合集
2019-03-12
Ubuntu初始化root密码
2019-03-12
编译android源代码(aosp)
2019-03-12
verilog一些小知识点注意事项集合
2019-03-12
C++的数据类型
2019-03-12
Java流程控制语句
2019-03-12
scratch3的作品(sb3格式的文件)怎么在移动端(手机)上进行播放呢
2019-03-12
wincc实现手机APP远程监控
2019-03-12
3.6.X版本的OSG无法打开osgShadow/ShadowVolume的问题
2019-03-12
LSM树
2019-03-12
Linux上elasticsearch7集群搭建
2019-03-12
打开网站工程时遇到配置bower显示404的问题。
2019-03-12
vue手写 头部 滑动按钮 点击查看更多,可折叠
2019-03-12
为什么 RTP 的视频的采样率是 90kHz ?
2019-03-12
IDEA快捷键CTRL+SHIFT+F无效
2019-03-12