I've 2 springboot
REST APIs REST-A & REST-B. REST-B is interacting with mongodb
for CRUD operations. And REST-A is calling REST-B endpoints for different reasons.
Controller in REST-B (Customer API)
public class CustomerController {
@Autowired
private CustomerRepository customerRepository;
@GetMapping(value = "/customers/{id}")
public ResponseEntity<Customer> getCustomerByExternalReferenceId(@PathVariable(value = "id") String id)
throws ResourceNotFoundException {
System.out.println("Customer id received :: " id);
Customer customer = customerRepository.findByExternalCustomerReferenceId(id)
.orElseThrow(() -> new ResourceNotFoundException("Customer not found for this id :: " id));
return ResponseEntity.ok().body(customer);
}
}
This endpoint works fine if I call from postman for both if customer found in DB and if customer not found in DB.
Now, if I try to call the same endpoint from REST-A and if customer found in DB I can get the response.
String url = "http://localhost:8086/customer-api/customers/{id}";
String extCustRefId =
setupRequest.getPayload().getCustomer().getCustomerReferenceId();
// URI (URL) parameters
Map<String, String> urlParams = new HashMap<>();
urlParams.put("id", extCustRefId); // here I tried with id that exists in DB and getting 200 ok response
HttpHeaders headers = new HttpHeaders();
headers.set("X-GP-Request-Id", "abc-xyz-123");
headers.set("Content-Type", "application/json");
headers.set("Accept", "application/json");
headers.set("Content-Length", "65");
String searchurl = UriComponentsBuilder.fromUriString(url).buildAndExpand(urlParams).toString();
System.out.println(searchurl);
HttpEntity request = new HttpEntity(headers);
RestTemplate restTemplate = new RestTemplate();
try {
ResponseEntity<String> response = restTemplate.exchange(
searchurl,
HttpMethod.GET,
request,
String.class
);
} catch (Exception e) {
e.printStackTrace();
}
But if there's no customer found from REST-B (Customer API) then I'm getting
http://localhost:8086/customer-api/customers/customer-528f2331-d0c8-46f6-88c2-7445ee6f4821
Customer id received :: customer-528f2331-d0c8-46f6-88c2-7445ee6f4821
org.springframework.web.client.HttpClientErrorException: 404 null
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:78)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
How do I call rest endpoint from one springboot
application to another and handle response properly?
CodePudding user response:
You can get the response body from HttpClientErrorException
as follows:
try {
ResponseEntity<String> response = restTemplate.exchange(
searchurl,
HttpMethod.GET,
request,
String.class
);
} catch (HttpClientErrorException e) {
String errorResponseBody = e.getResponseBodyAsString();
e.printStackTrace();
}
You can then use Jackson ObjectMapper
to map the String to a Java object.
CodePudding user response:
Try to use :
ResponseEntity.status(HttpStatus.NOT_FOUND).body("Customer not found for this id :: " id);
Full optional solution :
@GetMapping(value = "/customers/{id}")
public ResponseEntity<Customer> getCustomerByExternalReferenceId(@PathVariable(value = "id") String id){
System.out.println("Customer id received :: " id);
return customerRepository.findByExternalCustomerReferenceId(id)
.map(customer -> ResponseEntity.ok().body(customer))
.orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).body("Customer not found for this id :: " id));}
For handle any exception, you can use those solutions https://www.baeldung.com/exception-handling-for-rest-with-spring