package com.njcn.user.api.fallback;

import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.user.api.AuthClientFeignClient;
import com.njcn.user.pojo.po.AuthClient;
import com.njcn.user.utils.UserEnumUtil;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2021年12月15日 13:28
 */
@Slf4j
@Component
public class AuthClientFeignClientFallbackFactory implements FallbackFactory<AuthClientFeignClient> {

    /**
     * 输出远程请求接口异常日志
     * @param throwable RPC请求异常
     */
    @Override
    public AuthClientFeignClient create(Throwable throwable) {
        //判断抛出异常是否为解码器抛出的业务异常
        Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
        if(throwable.getCause() instanceof BusinessException){
            BusinessException businessException = (BusinessException) throwable.getCause();
            exceptionEnum = UserEnumUtil.getExceptionEnum(businessException.getResult());
        }
        Enum<?> finalExceptionEnum = exceptionEnum;
        return new AuthClientFeignClient() {
            @Override
            public HttpResult<AuthClient> getAuthClientByName(String clientName) {
                log.error("{}异常，降级处理，异常为：{}","根据客户端名称获取客户端信息",throwable.toString());
                throw new BusinessException(finalExceptionEnum);
            }
        };
    }
}
