grpc / grpc/grpc-java

Feature: StatusException and StatusRuntimeException utility methods

Open
#3,425 2 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Java
Stars
12.1k
Forks
4k
Avg merge
2d 17h
Merged PRs (30d)
37

Description

I'd like to propose adding additional static utility methods to the `Status` class to simplify common patterns for dealing with `StatusException` and `StatusRuntimeException`. Since SE and SRE are unrelated, working with them cannot be done with polymorphism.

I'd like to propose the following additional API for `Status`:
```java
public static boolean hasStatus(Throwable t)
public static boolean hasStatusCode(Throwable t, Status.Code code)
public static void doWithStatus(Throwable t, BiConsumer action)
```
These methods support handling gRPC statuses like:
```java
Futures.addCallback(
response,
new FutureCallback() {
@Override
public void onFailure(Throwable t) {
if (hasStatusCode(t, Status.Code.NOT_FOUND)) {
// If you are prepared for the error's status code, handle it
doWithStatus(t, (status, metadata) -> dealWithNotFoundStatus(status));
} else if (hasStatus(t)) {
// Other gRPC errors can be handled generically
doWithStatus(t, (status, metadata) -> handleGrpcProblem(status, metadata));
} else {
// Other non-grpc exceptions are handled normally
dealWithUnknownException(t);
}
}
},
executor);
```
The above code can be written using the existing APIs, but requires multiple nested if statements and `instanceof` checks.
```java
Futures.addCallback(
response,
new FutureCallback() {
@Override
public void onFailure(Throwable t) {
if (t instanceof StatusRuntimeException || t instanceof StatusException) {
Status status = Status.fromThrowable(t);
Metadata trailers = Status.trailersFromThrowable(t);
if (status == Status.Code.NOT_FOUND) {
// If you are prepared for the error's status code, handle it
dealWithNotFoundStatus(status);
} else {
// Other gRPC errors can be handled generically
handleGrpcProblem(status, metadata);
}
} else {
// Other non-grpc exceptions are handled normally
dealWithUnknownException(t);
}
}
},
executor);
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.