如何将异常从内部 doOnError 传播到外部 doOnError?

How to propagate exception from inner doOnError into outer doOnError?

我有 pay 方法,我应该在其中调用 initiatePayment,onSuccess 我应该调用 confirmPayment。 如果两个调用中的任何一个出现异常,它应该发出异常

public Single<PayResponse> pay(PayRequest apiRequest) {

            return client.initiatePayment(apiRequest)
                    .doOnSuccess(initiatePaymentResponse -> {
                        client.confirmPayment(initiatePaymentResponse.getPaymentId())
                                .doOnSuccess(confirmPaymentResponse -> doConfirmationLogic(confirmPaymentResponse ))
                                .doOnError(ex -> {ex.printStackTrace();logError(ex);});
                    })

                    .doOnError(ex -> {ex.printStackTrace();logError(ex);});
        }

在我引用的代码中,confirmPayment 发生错误,但 initiatePayment 继续正常。

如何将异常从内部 doOnError 传播到外部 doOnError

doOnXxx() 方法仅用于回调目的,它们不涉及流媒体管道,这就是它们被称为 "side-effect methods" 的原因。因此无法将错误从 doOnXxx() 传播到上游。

错误始终是 Rx 世界中的终端事件,只要发生错误,管道就会被取消,因此无需对 doOnSuccess() 方法做任何事情来确保到目前为止一切都是 "ok"。因此,无需将代码嵌套到 doOnSuccess() 链中,您可以简单地这样写:

/*
        you can deal with errors using these operators:

        onErrorComplete
        onErrorResumeNext
        onErrorReturn
        onErrorReturnItem
        onExceptionResumeNext
        retry
        retryUntil
        retryWhen
         */
        return client.initiatePayment(apiRequest)
                //if in initiatePayment was error this will send cancel upstream and error downstream
                .map(initiatePaymentResponse -> { client.confirmPayment(initiatePaymentResponse.getPaymentId());})
                //if in confirmPayment was error this never happens
                .map(confirmPaymentResponse -> doConfirmationLogic(confirmPaymentResponse))
                //every error in this pipeline will trigger this one here
                .doOnError(ex -> {
                    ex.printStackTrace();
                    logError(ex);
                });