package com.hotent.base.feign.error;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import com.hotent.base.exception.BaseException;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.JsonUtil;

import feign.FeignException;
import feign.Response;
import feign.RetryableException;
import feign.codec.ErrorDecoder;

/**
 * 自定义feign异常信息返回
 * @author jason
 *
 */
@Configuration
public class FeignErrorDecoder extends ErrorDecoder.Default {
	
	private static final Logger log = LoggerFactory.getLogger(FeignErrorDecoder.class);
	 @Override
    public Exception decode(String methodKey, Response response) {
        Exception exception = super.decode(methodKey, response);

        // 如果是RetryableException，则返回继续重试
        if (exception instanceof RetryableException) {
            return exception;
        }

        try {
            // 如果是FeignException，则对其进行处理，并抛出BaseException
            if (exception instanceof FeignException && ((FeignException) exception).responseBody().isPresent()) {
                ByteBuffer responseBody = ((FeignException) exception).responseBody().get();
                String bodyText = StandardCharsets.UTF_8.newDecoder().decode(responseBody.asReadOnlyBuffer()).toString();
        		String errorMsg = bodyText;
                try {
    				CommonResult<?> bean = JsonUtil.toBean(bodyText, CommonResult.class);
    				errorMsg = bean.getMessage();
    			} catch (Exception e) {
    			}
                return new BaseException(errorMsg);
               
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return exception;
    }
}
