package cn.com.taiji.beidou.ship.feign;

import com.alibaba.fastjson2.JSONObject;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;

/**
 * @Description:
 * @Author: hujie@umisoft.cn
 * @Date: 2020/4/8 6:31 PM
 */
@Slf4j
public class FastjsonFeignDecoder implements Decoder {

    @Override
    public Object decode(Response response, Type type) throws FeignException {
        if (response.status() == 404) {
            this.error("404错误");
            return Util.emptyValueOf(type);
        } else if (response.body() == null) {
            this.debug("检测到body区域数据为空");
            return null;
        }
        try {
            String result = Util.toString(response.body().asReader());
            this.debug(result);
            return JSONObject.parse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void debug(String message) {
        log.debug("FastjsonFeignDecoder >>>> 远端返回数据为：\n{}", message);
    }
    public void error(String message) {
        log.error("FastjsonFeignDecoder >>>> 发生错误：\n{}", message);
    }
}
