异常期间不进入错误处理块

Not entering error handling block during exception

在下面的方法中,我故意让调用 c.rxCommit() 在测试期间抛出异常。 异常按预期抛出,但我从未按预期进入 onErrorResumeNext 块。

我期待着陆在这里来处理错误并执行一些回滚。 我能得到一些关于为什么我没有在错误块内着陆的建议吗?谢谢

public Observable<Void> myMethod(Observable<Map<String, String>> records) {

    return client.rxGetConnection()
            .flatMapCompletable(c -> c.rxSetAutoCommit(false)
                    .toCompletable()
                    .andThen(records.flatMapSingle(record -> perform(c, record)).toCompletable())
                    .andThen(c.rxCommit().toCompletable()) // test makes this c.rxCommit() throw an error on purpose. 
                    .onErrorResumeNext(throwable -> {
                        // I want to land in here when error but it is not happening.
                        return c.rxRollback().toCompletable();
                    })
                    .andThen(c.rxSetAutoCommit(true).toCompletable())
                    .andThen(c.rxClose()).toCompletable()
            ).toObservable();
}

测试

@Test
void test() {
    when(sqlConnection.rxCommit()).thenThrow(new RuntimeException("Error on Commit")); // mockito
    myClass.myMethod(mockedRecords).subscribe(
            success -> System.out.println(),
            throwable -> System.out.println("err " + throwable), // I land in here with the new RuntimeException("Error on Commit") exception. 
            // this is wrong. Error should have been handled in the onErrorResumeNext block and should be getting success here instead. 
    );

    // some verify() to test outcome
}

正如 akarnokd 所说,您的 sqlConnection.rxCommit() 模拟是错误的,因为它在方法调用后立即抛出异常,而不是通过订阅。

如果想在 rx 流程中收到错误,试试这个:

when(sqlConnection.rxCommit()).thenReturn(Single.error(RuntimeException("Error on Commit")));

但如果你真的想在 rxCommit() 中抛出异常,请尝试将其包装在 Single.defer:

.andThen(
    Single.defer(() -> {
        return c.rxCommit().toCompletable();
})