package com.njcn.supervision.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.supervision.api.CheckDeviceFeignClient;
import com.njcn.supervision.utils.SupervisionEnumUtil;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author denghuajun
 * @version 1.0.0
 * @date 2022/3/16
 */
@Slf4j
@Component
public class CheckDeviceFeignClientFallbackFactory implements FallbackFactory<CheckDeviceFeignClient> {
    @Override
    public CheckDeviceFeignClient create(Throwable throwable) {
        //判断抛出异常是否为解码器抛出的业务异常
        Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
        if (throwable.getCause() instanceof BusinessException) {
            BusinessException businessException = (BusinessException) throwable.getCause();
            exceptionEnum = SupervisionEnumUtil.getExceptionEnum(businessException.getResult());
        }
        Enum<?> finalExceptionEnum = exceptionEnum;
        return new CheckDeviceFeignClient() {
            @Override
            public HttpResult<String> add() {
                log.error("{}异常，降级处理，异常为：{}", "新增终端检测数据", throwable.toString());
                throw new BusinessException(finalExceptionEnum);
            }
        };
    }
}
