Reputation: 667
cConsider the below class, when a 400 BAD_REQUEST is thrown by the rest call, I expect the HttpStatusCodeException to get caught, but instead it catches unexpected error Exception and throws an Internal Server Error. Why is HttpStatusCodeException not caught when a "BAD_REQUEST" is thrown?
class Abc {
@Autowired
RestTemplate template;
void connect(){
ResponseEntity<String> response;
try{
response=restTemplate.postForEntity("url", HTTP_ENTITY, String.class);
} catch( HttpStatusCodeException ex){
throws new CustomErrorResponse(ex.getStatusCode());
} catch (Exception ex){
throws new CustomErrorResponse(Internal_Server_Error);
}
}
}
JUnit Testcases
when(restTemplate.postForEntity(anyString(),any(),eq(String.class))).thenThrow(new CustomErrorResponse(HttpStatus.BAD_REQUEST));
But Internal Server is thrown
Upvotes: 1
Views: 1569
Reputation: 71
Your test case with restTemplate then throws CustomErrorResponse
not HttpStatusCodeException
Solution:
when(restTemplate.postForEntity(anyString(),any(),eq(String.class))).thenThrow(new HttpStatusCodeException(..));
Upvotes: 1
Reputation: 879
If the connect
method can have a different return type, the easiest way would be to return a ResponseEntity
and pass the status code in to that.
ResponseEntity<Object> connect(){
ResponseEntity<String> response;
try{
response=restTemplate.postForEntity("url", HTTP_ENTITY, String.class);
} catch( HttpStatusCodeException ex){
response = new ResponseEntity<>("There was an issue with the POST call.", ex.getStatusCode());
} catch (Exception ex){
throws new CustomErrorResponse(Internal_Server_Error);
}
return responseEntity;
}
Upvotes: 0