package cn.quantgroup.customer.config.rest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;

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

/**
 * @author Jie.Feng
 * @date 2018/2/6
 */
@Slf4j
public class HttpResponseErrorHandler extends DefaultResponseErrorHandler {

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        HttpStatus statusCode = getHttpStatusCode(response);
        Charset charset = getCharset(response);
        if (charset == null) {
            charset = Charset.defaultCharset();
        }
        switch (statusCode.series()) {
            case CLIENT_ERROR:
                byte[] responseBody = getResponseBody(response);
                log.warn("HTTP Response: statusCode={},body={}", statusCode, new String(responseBody, charset));
                throw new HttpClientErrorException(statusCode, response.getStatusText(),
                        response.getHeaders(), responseBody, charset);
            case SERVER_ERROR:
                byte[] responseBody2 = getResponseBody(response);
                log.warn("HTTP Response: statusCode={},body={}", statusCode, new String(responseBody2, charset));
                throw new HttpServerErrorException(statusCode, response.getStatusText(),
                        response.getHeaders(), responseBody2, charset);
            default:
                throw new RestClientException("Unknown status code [" + statusCode + "]");
        }
    }
}
