I’m working on a simple Spring Boot project and I want to create a response object for 500 error.
This is the controller:
@RestController
@Slf4j
public class DataController {
@PostMapping(value = "/data", consumes = "application/json", produces = "application/json")
DataResponse createData(@RequestBody List<ClientRequest> completeRequest) throws Exception {
log.info("completeRequest = {}", completeRequest);
throw new Exception();
}
Error
@Data
@Builder
@AllArgsConstructor
public class ErrorDTO {
private final String code;
private final String message;
private final String text;
}
Exception handler:
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseBody
@ExceptionHandler
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorDTO handleException(Exception exception) {
log.error(exception.getMessage(), exception);
return ErrorDTO.builder()
.code(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
.message("Unexpected error!")
.text("This is the text!")
.build();
}
}
When I call this API from Postman everything is fine and I get 500 Internal Server Error with response body:
{
"code": "Internal Server Error",
"message": "Unexpected error!",
"text": "This is the text!"
}
But the problem is when I try to call this API from another microservice. I’m using RestTemplate like that:
try {
ResponseEntity<ResponseDemo> result = restTemplate.postForEntity(uri, requestDemos, ResponseDemo.class);
log.info("Success response: {}", result);
ResponseDemo body = result.getBody();
log.info("body= {}", body);
} catch (HttpClientErrorException | HttpServerErrorException ex) {
log.error("ERROR at POST {}", ex.getMessage());
}
I receive only 500 Internal Server Error, I can’t find the Response Body
{
"code": "Internal Server Error",
"message": "Unexpected error!",
"text": "This is the text!"
}
Can someone explain how to receive the response body also in the other service, not only in Postman? Thank you!