I am trying to cover all of the rest template calls in my class for exception handling. Using Custom exception handling with error handler in spring boot application.
For this i have created a rest template bean in config and set error handler in it to the custom error handler class that i created with extends DefaultResponseErrorHandler.
public class BaseConfig {
@Bean
@Primary
RestTemplate restTemplate(@Autowired RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.errorHandler(new IPSRestErrorHandler()).build();
}
}
@Component
public class IPSRestErrorHandler extends DefaultResponseErrorHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(IPSRestErrorHandler.class);
@Override
public void handleError(ClientHttpResponse response) throws IOException {
if (response.getStatusCode()
.series() == HttpStatus.Series.SERVER_ERROR) {
LOGGER.error("Server error with exception code : "+response.getStatusCode()+" with message : "+response.getStatusText());
throw ExceptionUtils.newRunTimeException("Server error with exception code : "+response.getStatusCode()+" with message : "+response.getStatusText());
} else if (response.getStatusCode()
.series() == HttpStatus.Series.CLIENT_ERROR) {
LOGGER.error("Client error with exception code : "+response.getStatusCode()+" with message : "+response.getStatusText());
throw ExceptionUtils.newRunTimeException("Client error with exception code : "+response.getStatusCode()+" with message : "+response.getStatusText());
} else {
LOGGER.error("Unknown HttpStatusCode with exception code : "+response.getStatusCode()+" with message : "+response.getStatusText());
throw ExceptionUtils.newRunTimeException("Unknown HttpStatusCode with exception code : "+response.getStatusCode()+" with message :"+response.getStatusText());
}
}
}
public class ServicingPlatformSteps {
@Autowired
private RestTemplate restTemplate;
private ResponseEntity callServicingPlatformAPI(RemittanceV2Input inputClass) {
ResponseEntity entity = null;
entity = restTemplate.exchange(builder.build().encode().toUri(),
org.springframework.http.HttpMethod.POST, httpEntity, typeRef);
return entity;
}
Here i am expecting that when restTemplate.exchange method is called and it throws some exception then my IPSRestErrorHandler should be called. But error handler is not getting called. While i am getting this restTemplate instance with error handler info in it.
Could you please help me why error handler is not getting called?