Skip to content

Instantly share code, notes, and snippets.

@sachin-handiekar
Created August 22, 2025 13:53
Show Gist options
  • Save sachin-handiekar/adbbc288a24756f04d4486e3647be488 to your computer and use it in GitHub Desktop.
Save sachin-handiekar/adbbc288a24756f04d4486e3647be488 to your computer and use it in GitHub Desktop.
CustomErrorHandler - Spring Rest Template
package com.example.resttemplatedemo.handler;
import com.example.resttemplatedemo.exception.CustomExceptions;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class CustomErrorHandler implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode().is4xxClientError() ||
response.getStatusCode().is5xxServerError();
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
String responseBody = new String(response.getBody().readAllBytes(), StandardCharsets.UTF_8);
HttpStatus statusCode = (HttpStatus) response.getStatusCode();
switch (statusCode) {
case BAD_REQUEST:
throw new CustomExceptions.BadRequestException(
"Bad Request: " + statusCode.getReasonPhrase(), responseBody);
case UNAUTHORIZED:
throw new CustomExceptions.UnauthorizedException(
"Unauthorized: " + statusCode.getReasonPhrase(), responseBody);
case FORBIDDEN:
throw new CustomExceptions.ForbiddenException(
"Forbidden: " + statusCode.getReasonPhrase(), responseBody);
case NOT_FOUND:
throw new CustomExceptions.NotFoundException(
"Not Found: " + statusCode.getReasonPhrase(), responseBody);
case INTERNAL_SERVER_ERROR:
throw new CustomExceptions.InternalServerErrorException(
"Internal Server Error: " + statusCode.getReasonPhrase(), responseBody);
case SERVICE_UNAVAILABLE:
throw new CustomExceptions.ServiceUnavailableException(
"Service Unavailable: " + statusCode.getReasonPhrase(), responseBody);
default:
throw new CustomExceptions.ApiException(
"HTTP Error: " + statusCode.getReasonPhrase(),
statusCode.value(), responseBody);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment