liurunyu
2023-11-18 c1ddfd71223c1a7d704b6f21b669fbfcb37adc82
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
package com.dy.common.webUtil;
 
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
 
/**
 * 全局异常处理,处理在Controller中抛出的异常,在Controller之前(如Fileter)发生的错误或异常由GlErrorCtrl处理
 * 此类是基于注解切面实现,
 * 另一种实现方式是基于拦截器和实现指定接口(GlExceptionHandler)
 */
//@Tag(name = "全局异常处理", description = "处理在Controller中抛出的异常,在Controller之前(如Fileter)发生的错误或异常由GlErrorCtrl处理")
//@Aspect
@Slf4j
//@Component
public class GlExceptionAspect {
 
    //@Pointcut("execution(* com.dy..*(..))")
    private void traceExceptionAspect() {
    }
 
    //@Around("traceExceptionAspect()")
    public Object around(ProceedingJoinPoint joinPoint) {
        String interfaceName = String.format("%s.%s", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        Object result;
        try {
            result = joinPoint.proceed();
        } catch (Throwable ex) {
            if (ex instanceof GlException) {
                GlException e = (GlException) ex;
                result = BaseResponseUtils.buildFail(e.getMsg());
                log.error(String.format("调用接口%s异常,错误信息:%s", interfaceName, e.getMsg()), e);
            } else {
                result = BaseResponseUtils.buildFail("在Controller中或后产生异常:" + ex.getMessage());
                log.error(String.format("调用接口%s异常,错误信息:%s", interfaceName, ex.toString()), ex);
            }
        }
        return result;
    }
}