package com.cm.central.control.client.socket.aspect;

import com.cm.central.control.client.socket.service.socket.exception.ExceptionServiceImpl;
import com.cm.common.exception.base.SystemException;
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.core.annotation.Order;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName: ApiLogAspect
 * @Description: 接口日志切面
 * @Author: WangGeng
 * @Date: 2019/3/14 9:33 AM
 * @Version: 1.0
 **/
@Aspect
@Component
@Order(3)
public class ClientExceptionAspect {

    @Resource(name = "exceptionServiceImpl")
    private ExceptionServiceImpl exceptionServiceImpl;

    /**
     * service切入点
     */
    @Pointcut("execution(public * com.cm..service..*.*(..)) && !execution(public * com.cm.central.control.client.socket.service..*.*(..))")
    public void serviceCutPoint() {
    }

    @Around("serviceCutPoint()")
    public Object appLogAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object result;
        try {
            result = proceedingJoinPoint.proceed();
        } catch (Throwable e) {
            boolean exceptionFlag = e instanceof SystemException
                    || e instanceof AuthenticationException
                    || e instanceof OAuth2Exception
                    || e instanceof ClientRegistrationException;
            if (!exceptionFlag) {
                new Thread(() -> {
                    exceptionServiceImpl.writeThrowable(e);
                }).start();
            }
            throw e;
        }
        return result;
    }

}
