在截止日期之前调用grpc阻止存根时如何管理应用程序崩溃

问题描述 投票:0回答:2

我正在尝试开发一个使用grpc阻止存根连接到后端服务器的应用。

我到了发出请求的地步,由于超过了截止日期,我的应用程序崩溃了。预期的行为是,当服务器无响应时(应用程序崩溃和关闭是不可接受的),try catch会处理。

以下是我的存根生成和错误:

    public LoginDataSource() {
    }

    public Result<LoggedInUser> login(String username, String password) {
        LoginServiceGrpc.LoginServiceBlockingStub blockingStub = LoginServiceGrpc.newBlockingStub(commChannel);
        GrpcServerComm.LoginData loginData = GrpcServerComm.LoginData.newBuilder().setUsername(username).setPassword(password).build();
        GrpcServerComm.LoginRequest serverResponse = blockingStub.withDeadlineAfter(2000, TimeUnit.MILLISECONDS).getLogin(loginData);
        long serverResponseVal = 0;
        try
        {
            LoggedInUser activeUser = new LoggedInUser(username,username);
            serverResponseVal = serverResponse.getResponseVal();
            return new Result.Success<>(activeUser);
        }
        catch (Exception e)
        {
            return new Result.Error(new IOException("Error logging in", e));
        }

    }

调试:

D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.equinox.openeyes, PID: 2401
    io.grpc.StatusRuntimeException: DEADLINE_EXCEEDED: deadline exceeded after 1766623100ns. [buffered_nanos=1774305900, waiting_for_connection]
        at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:240)
        at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:221)
        at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:140)
        at com.equinox.openeyes.LoginServiceGrpc$LoginServiceBlockingStub.getLogin(LoginServiceGrpc.java:155)
java android grpc channel
2个回答
0
投票

尝试一下

public MutableLiveDataResult<LoggedInUser> login(String username, String password) {

        MutableLiveDataResult<LoggedInUser> observeable = new MutableLiveDataResult<LoggedInUser>();
        LoginServiceGrpc.LoginServiceBlockingStub service = LoginServiceGrpc.newStub(commChannel);
        GrpcServerComm.LoginData loginData = GrpcServerComm.LoginData.newBuilder().setUsername(username).setPassword(password).build();
        service.getLogin(loginData, new StreamObserver<LoggedInUser> {

            public void onNext(LoggedInUser response) {
                observeable.postValue(response);
            }

            public void onError(Throwable t) {
                observeable.postValue(null);
            }

            public void onCompleted(Throwable t) {
                // if you wanna close your channel
                // commChannel.shutdown();
            } 
        })
        return observable;
    }

并观察MutableLiveData中的变化并在那里获得结果。


0
投票

我发现问题是我的阻塞存根调用需要在try catch中。

一旦将其移动到那里并将异常更改为StatusRuntimeExceotion,我便能够相应地处理该异常。

© www.soinside.com 2019 - 2024. All rights reserved.