【问题标题】:Java gRPC: exception from client to serverJava gRPC:从客户端到服务器的异常
【发布时间】:2020-10-13 05:38:50
【问题描述】:

是否可以从客户端向服务器抛出异常? 我们有一个从服务器到客户端的开放流:

rpc addStream(Request) returns (stream StreamMessage) {}     

当我尝试这样的事情时:

throw Status.INTERNAL.withDescription(e.getMessage()).withCause(e.getCause()).asRuntimeException();

我在客户端的StreamObserver.onError中得到了异常,但是在服务器端没有异常。

【问题讨论】:

    标签: grpc grpc-java


    【解决方案1】:

    服务器可以用存根 API 公开为 StatusRuntimeException 的“状态”进行响应。然而,客户端只能“取消” RPC。服务器将不知道取消的来源;可能是因为客户端取消了,也可能是 TCP 连接中断了。

    在客户端流式或双向流式调用中,客户端可以通过调用 observer.onError() 取消(无需调用 onCompleted())。但是,如果客户端调用onCompleted()或者RPC有一元请求,则需要使用ClientCallStreamObserverContext

    stub.someRpc(request, new ClientResponseObserver<Request, Response>() {
      private ClientCallStreamObserver<Request> requestStream;
    
      @Override public void beforeStart(ClientCallStreamObserver<Request> requestStream) {
        this.requestStream = requestStream;
      }
      ...
    });
    
    // And then where you want to cancel
    
    // RequestStream is non-thread-safe. For unary requests, wait until
    // stub.someRpc() returns, since it uses the stream internally.
    // The string is not sent to the server. It is just "echoed"
    // back to the client's `onError()` to make clear that the
    // cancellation was locally caused.
    requestStream.cancel("some message for yourself", null);
    
    
    // For thread-safe cancellation (e.g., for client-streaming)
    CancellableContext ctx = Context.current().withCancellation();
    StreamObserver requestObserver = ctx.call(() ->
      stub.someRpc(new StreamObserver<Response>() {
        @Override public void onCompleted() {
          // The ctx must be closed when done, to avoid leaks
          ctx.cancel(null);
        }
    
        @Override public void onError() {
          ctx.cancel(null);
        }
      }));
    
    // The place you want to cancel
    ctx.cancel(ex);
    

    【讨论】:

    • 感谢您的回答。在服务器流式调用中这怎么可能?
    • @silb78,server-streaming 有一个请求,所以它与一元请求相同。
    猜你喜欢
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多