package com.usky.common.security.feign;

import com.alibaba.fastjson.JSON;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.exception.BusinessException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

@Slf4j
public class OpenFeignErrorDecoder implements ErrorDecoder {
    /**
     * Feign异常解析
     * @param methodKey 方法名
     * @param response 响应体
     * @return BizException
     */
    @Override
    public Exception decode(String methodKey, Response response) {
        log.error("feign client error,response is {}:",response);
        try {
            //获取数据
            String body = Util.toString(response.body().asReader(Charset.defaultCharset()));

            ApiResult<?> resultData = JSON.parseObject(body,ApiResult.class);
            if(!resultData.isSuccess()){
                return new BusinessException(resultData.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new BusinessException("Feign client 调用异常");
    }
}
