dosubot[bot] commented on issue #2776:
URL:
https://github.com/apache/incubator-hugegraph/issues/2776#issuecomment-2911912071
<!-- Answer -->
HugeGraph-Client Java 没有直接提供“判断顶点是否存在且不抛异常”的专用接口,但你可以通过调用
`vertexAPI.get(id)` 并捕获异常来实现类似效果。官方测试用例(如 VertexApiTest.java)就是这样做的:
- 如果顶点存在,`vertexAPI.get(id)` 会返回顶点对象。
- 如果顶点不存在,会抛出异常(底层是 HTTP 404),你可以捕获这个异常来判断不存在。
示例代码(伪代码):
```java
import org.apache.hugegraph.client.HugeClient;
import org.apache.hugegraph.exception.ServerException;
import org.apache.hugegraph.structure.graph.Vertex;
public boolean vertexExists(HugeClient client, Object id) {
try {
Vertex v = client.graph().getVertex(id);
return v != null;
} catch (ServerException e) {
// HugeGraph-Client 会在 404 时抛出 ServerException
if (e.status() == 404) {
return false;
}
throw e; // 其他异常继续抛出
}
}
```
参考官方测试代码片段([VertexApiTest.java](https://github.com/apache/incubator-hugegraph-toolchain/blob/master/hugegraph-client/src/test/java/org/apache/hugegraph/api/VertexApiTest.java)):
```java
public void testGetNotExist() {
Utils.assertResponseError(404, () -> {
vertexAPI.get("not-exist-vertex-id");
});
}
```
目前 HugeGraph-Client Java 没有像 RESTful API 那样直接返回 404
状态码的“存在性判断”接口,只能通过捕获异常来实现。如果你希望完全不依赖异常,可以考虑直接用 HTTP 客户端请求 RESTful API 并判断状态码。
如需更详细的代码示例或有其他需求,可以继续补充说明。
<!-- Dosu Comment Footer -->
*To reply, just mention my name [@dosu](https://go.dosu.dev/dosubot).*
---
<sup>How did I do?
[Good](https://app.dosu.dev/response-feedback/cfa045e9-4af1-4cad-a78a-c0ac22ea97af?feedback_type=great_response)
|
[Irrelevant](https://app.dosu.dev/response-feedback/cfa045e9-4af1-4cad-a78a-c0ac22ea97af?feedback_type=irrelevant_answer)
|
[Incorrect](https://app.dosu.dev/response-feedback/cfa045e9-4af1-4cad-a78a-c0ac22ea97af?feedback_type=incorrect_sources)
|
[Verbose](https://app.dosu.dev/response-feedback/cfa045e9-4af1-4cad-a78a-c0ac22ea97af?feedback_type=too_verbose)
|
[Hallucination](https://app.dosu.dev/response-feedback/cfa045e9-4af1-4cad-a78a-c0ac22ea97af?feedback_type=hallucination)
| [Report
🐛](https://app.dosu.dev/response-feedback/cfa045e9-4af1-4cad-a78a-c0ac22ea97af?feedback_type=bug_report)
|
[Other](https://app.dosu.dev/response-feedback/cfa045e9-4af1-4cad-a78a-c0ac22ea97af?feedback_type=other)</sup> [](https://go.dosu.dev/discord-bot) [!
[Share on
X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/apache/incubator-hugegraph/issues/2776)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]