package ru.nbch.credit_tracker.config.rest;

import lombok.extern.slf4j.Slf4j;
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 java.io.IOException;

@Slf4j
public class ResponseErrorHandler extends DefaultResponseErrorHandler {
    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        if (response.getStatusCode().is4xxClientError()) {
            throw new HttpClientErrorException(
                    response.getStatusCode(),
                    "Client error: " + response.getStatusText(),
                    response.getBody().readAllBytes(),
                    null
            );
        } else if (response.getStatusCode().is5xxServerError()) {
            throw new HttpServerErrorException(
                    response.getStatusCode(),
                    "Server error: " + response.getStatusText(),
                    response.getBody().readAllBytes(),
                    null
            );
        }
        super.handleError(response);
    }
}
