简体   繁体   中英

How to handle no data found when calling restTemplate.getForObject

I am calling restTemplate.getForObject to retrieve a certain value from Mongo DB. How to deal the exception if the expected data is not found in the DB?

Object[] mongodata = restTemplate.getForObject(resulturl,Object[].class,keyval);
list = Arrays.asList(mongodata); 

where keyval is a string that contains a json and resulturl is the url for calling mongo

Basically, you have two main options:

  1. Simply wrap the RestTemplate call in a try-catch block and handle the error (in case of 404 not found response, it would be the HttpClientErrorException ). Something like
try {
  Object[] mongodata = restTemplate.getForObject(resulturl,Object[].class,keyval);
  list = Arrays.asList(mongodata);
} catch (HttpClientErrorException e) {
  if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
    // Do something
  } else {
    throw e;
  } 
}
  1. Implement a ResponseErrorHandler .

See this post on Baeldung for an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM