package com.yeejoin.amos.supervision.business.feign;


import com.alibaba.fastjson.JSONObject;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author DELL
 */
@Slf4j
public class FeignClientErrorDecoder extends ErrorDecoder.Default {

    @Override
    public Exception decode(String methodKey, Response response) {
        Exception exception = super.decode(methodKey, response);
        String message;
        try {
            if (exception instanceof FeignException && ((FeignException) exception).responseBody().isPresent()) {
                String body = Util.toString(response.body().asReader());
                JSONObject jsonObject = JSONObject.parseObject(body);
                message = jsonObject.getString("devMessage");
                return new RuntimeException(message);
            }
        } catch (IOException e) {
            log.error("feign.IOException", e);
        }
        return exception;
    }
}
