/**
 * 
 */
package org.springblade.openfeign.error;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.springframework.context.annotation.Configuration;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import feign.Response;
import feign.Response.Body;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 *
 */
@Slf4j
@Configuration
public class FeignClientErrorDecoder implements ErrorDecoder {

	@Override
	public Exception decode(String methodKey, Response response) {
		try {
			Body body = response.body();
			if(body != null) {
				String errorContent = Util.toString(body.asReader(StandardCharsets.UTF_8));
				JSONObject jsonObject = JSONUtil.parseObj(errorContent);
				//当httpStatus!=200时，data返回值为errorMsg
				String serverErrorMsg = jsonObject.getStr("data"),
					   //serverData = jsonObject.getStr("data", ""),
					   serverExt = jsonObject.getStr("ext", "");
				return new RuntimeException(String.format("%s %s", serverErrorMsg, serverExt));
			}
		} catch (IOException e) {
			log.error("FeignClientErrorDecoder decode exception:{}.", e);
            return e;
		}
		return new RuntimeException("服务端未知异常!");
	}

}
