Issue
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
Solution
Your test case with restTemplate then throws CustomErrorResponse
not HttpStatusCodeException
Solution:
when(restTemplate.postForEntity(anyString(),any(),eq(String.class))).thenThrow(new HttpStatusCodeException(..));
Answered By - Ngo Tuoc
Answer Checked By - Pedro (JavaFixing Volunteer)