package com.liquidnet.common.feign.config;

import com.alibaba.fastjson.JSON;
import com.liquidnet.service.constant.GlobalConstant;
import com.liquidnet.common.exception.constant.ErrorCode;
import com.liquidnet.common.exception.entity.Error;
import com.liquidnet.common.exception.LiquidnetFeignException;
import feign.Response;
import feign.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * 业务异常处理
 * Created by Administrator on 2017/7/15.
 */
@Configuration
public class BizExceptionFeignErrorDecoder implements feign.codec.ErrorDecoder {

    private static final Logger logger = LoggerFactory.getLogger(BizExceptionFeignErrorDecoder.class);

    @Override
    public Exception decode(String methodKey, Response response) {
        LiquidnetFeignException ex = null;
        try {
            if(response.status() == 417 ){
                if (response.body() != null) {
                    String body = Util.toString(response.body().asReader());
                    logger.error(body);
                    Error error = JSON.parseObject(body, Error.class);
                    String message = error.getMessage();
                    message = message == null ? "" : message;
                    String code = error.getCode();
                    if (ErrorCode.getErrorCode(code) != null) {
                        ex = new LiquidnetFeignException(ErrorCode.getErrorCode(code), message);
                    }
                }
            }
        } catch (IOException var4) {
            var4.printStackTrace();
            ex = new LiquidnetFeignException(ErrorCode.ERROR, ErrorCode.HTTP_SYSTEM_ERROR.getMessage());
        }
        return null != ex ? ex : feign.FeignException.errorStatus(methodKey, response);
    }
}
