Search code examples
javamongodbresttemplaterestheart

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


Solution

  • 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.