简体   繁体   English

调用restTemplate.getForObject时如何处理未找到数据

[英]How to handle no data found when calling restTemplate.getForObject

I am calling restTemplate.getForObject to retrieve a certain value from Mongo DB.我正在调用restTemplate.getForObject从 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其中 keyval 是一个包含 json 的字符串,resulturl 是调用 mongo 的 url

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 ).只需将RestTemplate调用包装在try-catch块中并处理错误(如果 404 not found 响应,它将是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 .实现一个ResponseErrorHandler

See this post on Baeldung for an example.有关示例,请参阅 Baeldung 上的这篇文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 restTemplate.getForObject上的HttpClientErrorException - HttpClientErrorException on restTemplate.getForObject 如何对 Mediatypes Rest 端点进行 restTemplate.getForObject 调用 - How to make restTemplate.getForObject call for Mediatypes Rest endpoint 没有获得通过RestTemplate.getForObject传递的标头 - not getting headers passed with RestTemplate.getForObject Spring Boot 微服务 - 将授权标头添加到 restTemplate.getForObject - Spring Boot Microservices - Add authorization header to restTemplate.getForObject restTemplate.getForObject(“URL”,Object [] .class)可以返回NULL吗? - Can restTemplate.getForObject(“URL”, Object[].class) return NULL? Spring restTemplate.getForObject()的JSON转换错误 - JSON conversion error from Spring restTemplate.getForObject() 在 Android 中使用 restTemplate.getForObject 反序列化 JSON object 的正确方法 - Proper way to use restTemplate.getForObject to deserialize JSON object in Android 使用 RestTemplate getForObject 时无法捕获错误 - Unable to catch error when using RestTemplate getForObject 尝试 resttemplate getforobject 时出现 404 错误 - Getting 404 error when try to resttemplate getforobject 如何使用jmockit模拟RestTemplate getForObject方法? - How to mock RestTemplate getForObject method using jmockit?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM