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!
Depends on the problem you have.
(1) You get the response, but you don't know how to read it
Use HttpClientErrorException.getResponseBodyAsString() or similar method.
Alternatively you can implement ResponseErrorHandler for your restTemplate
.
(2) Server doesn't send you the response in JSON format
Add "Accept" request header with the value MediaType.APPLICATION_JSON
to let Spring know, you client supports JSON.
Spring tries to guess the response content type. Depends on configuration it falls back to plain/text
or some other "wrong" type without body.