0
Hello. I’m trying to override the Responseerrorhandler interface so I can return the entire request (status code, body etc.) in case of any answer other than 2xx.
I noticed that the default Spring (Resttemplate) returns an Exception in case of answer other than 2xx. This doesn’t help me much.
Following some tutorials, I found the following code:
@Component
public class LoginErrorHandler
        implements ResponseErrorHandler {
    @Override
    public boolean hasError(ClientHttpResponse httpResponse)
            throws IOException {
        return (
                httpResponse.getStatusCode().series() == CLIENT_ERROR
                        || httpResponse.getStatusCode().series() == SERVER_ERROR);
    }
    @Override
    public void handleError(ClientHttpResponse httpResponse)
            throws IOException {
        if (httpResponse.getStatusCode()
                .series() == SERVER_ERROR) {
            // handle SERVER_ERROR
        } else if (httpResponse.getStatusCode()
                .series() == CLIENT_ERROR) {
            // handle CLIENT_ERROR
        }
    }
But I didn’t understand how I’ll be able to return a Responseentity without changing the return method (which I can’t because I’m doing Override).
Implementation:
 //Objeto da requisição
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new LoginErrorHandler());
        //Disparando Request
        return restTemplate.postForEntity(url, request, String.class);
I return to Responseentity complete (thus, it provides the body, the status code and everything else in endpoint)
I would like to know how you do it. I was told "put everything inside a Try/catch and good", but this seems to me to gambiarra and, even trying, did not work:
//Disparando Request
        try {
            return restTemplate.postForEntity(url, request, String.class);
        } catch (HttpClientErrorException e) {
            errorCode = e.getRawStatusCode();
        }
        switch (errorCode){
            case 401:
                return new ResponseEntity(HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }
(does not return the body of the answer or anything. It is as if the answer simply did not exist in case of 4xx or 5xx!)