[英]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:基本上,您有两个主要选择:
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;
}
}
ResponseErrorHandler
.实现一个ResponseErrorHandler
。See this post on Baeldung for an example.有关示例,请参阅 Baeldung 上的这篇文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.