服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 解决Springboot全局异常处理与AOP日志处理中@AfterThrowing失效问题

解决Springboot全局异常处理与AOP日志处理中@AfterThrowing失效问题

2023-05-15 18:17Janson666 Java教程

这篇文章主要介绍了解决Springboot全局异常处理与AOP日志处理中@AfterThrowing失效问题,文中介绍了两种失效场景,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧

一、前言

  • 在实际业务场景中,我们通常会使用全局异常处理机制,也就是在业务代码发生异常的时候,拦截异常并进行统一的处理,然后以Json格式返回给前端。
  • 同时我们也会使用AOP进行操作日志记录,在不发生异常时,可以使用四种advice方式记录操作日志:@Before(“”),@After(“”)、 @AfterReturning(“”)、 @Around(“”)。当发生异常时,使用@AfterThrowing(value = “”,throwing = “e”)进行日志记录。

二、问题

同时使用上述两种方式,可能出现某一种失效的场景。

三、失效场景

失效场景一: 如果采用前后端不分离架构,采用下属代码返回前端响应结果,如果统一异常处理执行顺序在@AfterThrowing之前,就会出现@AfterThrowing中不执行情况。前后端分离架构不会出现此问题。

?
1
2
3
4
5
6
7
8
String xRequestedWith = request.getHeader("x-requested-with");
if ("XMLHttpRequest".equals(xRequestedWith)) {
    response.setContentType("application/plain;charset=utf-8");
    PrintWriter writer = response.getWriter();
    writer.write(CommunityUtil.getJSONString(1, "服务器异常!"));
} else {
    response.sendRedirect(request.getContextPath() + "/error");
}

解决方案:让AOP日志处理类实现Ordered 接口,并重写getOrder()方法,使其返回值为1,返回值越小,执行的顺序越靠前,使其执行顺序优先于全部异常处理类。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Component
@Aspect
public class LogAspectTest implements Ordered {
    @Override
    public int getOrder() {
        return 1;
    }
        @AfterThrowing(value = "pointcut()",throwing = "e")
    public void afterThrowing(JoinPoint joinPoint,Exception e){
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        System.out.println("className is : " + className + ". methodName is : " + methodName);
        System.out.println("afterThrowing excute········" + e.getMessage());
        e.printStackTrace();
    }
}

失效场景二:如果使用了 @Around(“”),在执行 joinPoint.proceed()方法时,捕获了异常,会导致全局异常处理无法收到异常,因此失效。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Around("pointcut()")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
    String className = joinPoint.getTarget().getClass().getName();
    String methodName = joinPoint.getSignature().getName();
    System.out.println("className is : " + className + ". methodName is : " + methodName);
    System.out.println("around excute before ········");
    Object obj = null;
    try {
        obj = joinPoint.proceed();
    } catch (Throwable e) {
        System.out.println("我捕获了异常");
    }
    System.out.println("obj 对象: " + obj);
    System.out.println("around excute after ········");
}

解决方案:不要进行异常捕获,或者捕获后重新抛出异常。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Around("pointcut()")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
    String className = joinPoint.getTarget().getClass().getName();
    String methodName = joinPoint.getSignature().getName();
    System.out.println("className is : " + className + ". methodName is : " + methodName);
    System.out.println("around excute before ········");
    Object obj = null;
    try {
        obj = joinPoint.proceed();
    } catch (Throwable e) {
        System.out.println("我捕获了异常");
        throw new RuntimeException("执行失败",e);
    }
    System.out.println("obj 对象: " + obj);
    System.out.println("around excute after ········");
}

4、测试全部代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package com.nowcoder.community.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
 * @Description aop 日志记录
 */
@Component
@Aspect
public class LogAspectTest implements Ordered {
    /**
     * 定义执行顺序的优先级,值越小,优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
    /**
     * 定义切点(织入点)
     *  execution(* com.nowcoder.community.controller.*.*(..))
     *      - 第一个 * 表示 支持任意类型返回值的方法
     *      - com.nowcoder.community.controller 表示这个包下的类
     *      - 第二个 * 表示 controller包下的任意类
     *      - 第三个 * 表示 类中的任意方法
     *      - (..) 表示方法可以拥有任意参数
     *   可以根据自己的需求替换。
     *
     */
    @Pointcut("execution(* com.nowcoder.community.controller.*.*(..))")
    public void pointcut(){
    }
    /**
     * 定义 advice 通知
     *    - 1. @Before 目标方法执行之前
     *    - 2. @After  目标方法执行之后
     *    - 3. @AfterReturning 目标方法返回执行结果之后
     *    - 4. @AfterThrowing 目标方法抛出异常后
     *    - 5. @Around 可以使用ProceedingJoinPoint joinPoint,获取目标对象,通过动态代理,代理目标类执行,在目标对象执行前后均可
     */
    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }
        // 请求ip
        String ip = attributes.getRequest().getRemoteHost();
        // 请求路径
        String requestURI = attributes.getRequest().getRequestURI();
        // 请求方法
        String requestMethod = attributes.getRequest().getMethod();
        System.out.println(String.format("用户: [%s] 的请求路径为:[%s], 请求方式为: [%s],请求类名为: [%s], 请求方法名为: [%s]", ip,requestURI,
                requestMethod,className,methodName));
        System.out.println("before excute········");
    }
    @After("pointcut()")
    public void after(JoinPoint joinPoint){
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }
        // 请求ip
        String ip = attributes.getRequest().getRemoteHost();
        // 请求路径
        String requestURI = attributes.getRequest().getRequestURI();
        // 请求方法
        String requestMethod = attributes.getRequest().getMethod();
        System.out.println(String.format("用户: [%s] 的请求路径为:[%s], 请求方式为: [%s],请求类名为: [%s], 请求方法名为: [%s]", ip,requestURI,
                                         requestMethod,className,methodName));
        System.out.println("after excute········");
    }
    @AfterReturning("pointcut()")
    public void afterReturning(JoinPoint joinPoint){
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }
        // 请求ip
        String ip = attributes.getRequest().getRemoteHost();
        // 请求路径
        String requestURI = attributes.getRequest().getRequestURI();
        // 请求方法
        String requestMethod = attributes.getRequest().getMethod();
        System.out.println(String.format("用户: [%s] 的请求路径为:[%s], 请求方式为: [%s],请求类名为: [%s], 请求方法名为: [%s]", ip,requestURI,
                                         requestMethod,className,methodName));
        System.out.println("afterReturning excute········");
    }
    @AfterThrowing(value = "pointcut()",throwing = "e")
    public void afterThrowing(JoinPoint joinPoint,Exception e){
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }
        // 请求ip
        String ip = attributes.getRequest().getRemoteHost();
        // 请求路径
        String requestURI = attributes.getRequest().getRequestURI();
        // 请求方法
        String requestMethod = attributes.getRequest().getMethod();
        System.out.println(String.format("用户: [%s] 的请求路径为:[%s], 请求方式为: [%s],请求类名为: [%s], 请求方法名为: [%s],请求失败原因: [%s]", ip,
                                         requestURI, requestMethod,className,methodName,e.getMessage()+e.getCause()));
        System.out.println("afterThrowing excute········" + e.getMessage());
        e.printStackTrace();
    }
    @Around("pointcut()")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        System.out.println("className is : " + className + ". methodName is : " + methodName);
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }
        // 请求ip
        String ip = attributes.getRequest().getRemoteHost();
        // 请求路径
        String requestURI = attributes.getRequest().getRequestURI();
        // 请求方法
        String requestMethod = attributes.getRequest().getMethod();
        System.out.println(String.format("用户: [%s] 的请求路径为:[%s], 请求方式为: [%s],请求类名为: [%s], 请求方法名为: [%s]", ip,requestURI,
                                         requestMethod,className,methodName));
        Object obj = null;
        try {
            obj = joinPoint.proceed();
        } catch (Throwable e) {
            System.out.println("我捕获了异常");
            throw new RuntimeException("执行失败",e);
        }
        System.out.println(String.format("用户: [%s] 的请求路径为:[%s], 请求方式为: [%s],请求类名为: [%s], 请求方法名为: [%s]", ip,requestURI,
                                         requestMethod,className,methodName));
        System.out.println("around excute after ········");
    }
}

到此这篇关于解决Springboot全局异常处理与AOP日志处理中@AfterThrowing失效问题的文章就介绍到这了,更多相关Springboot @AfterThrowing失效内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_42102911/article/details/130647814

延伸 · 阅读

精彩推荐