Java Examples for rx.exceptions.CompositeException

The following java examples will help you to understand the usage of rx.exceptions.CompositeException. These source code samples are taken from different open source projects.

Example 1
Project: retrofit-master  File: SingleThrowingTest.java View source code
@Test
public void bodyThrowingInOnErrorDeliveredToPlugin() {
    server.enqueue(new MockResponse().setResponseCode(404));
    final AtomicReference<Throwable> pluginRef = new AtomicReference<>();
    RxJavaPlugins.getInstance().registerErrorHandler(new RxJavaErrorHandler() {

        @Override
        public void handleError(Throwable throwable) {
            if (!pluginRef.compareAndSet(null, throwable)) {
                // Don't swallow secondary errors!
                throw Exceptions.propagate(throwable);
            }
        }
    });
    RecordingSubscriber<String> observer = subscriberRule.create();
    final AtomicReference<Throwable> errorRef = new AtomicReference<>();
    final RuntimeException e = new RuntimeException();
    service.body().subscribe(new ForwardingObserver<String>(observer) {

        @Override
        public void onError(Throwable throwable) {
            if (!errorRef.compareAndSet(null, throwable)) {
                throw Exceptions.propagate(throwable);
            }
            throw e;
        }
    });
    CompositeException composite = (CompositeException) pluginRef.get();
    assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
Example 2
Project: Intro-To-RxJava-master  File: MergeDelayErrorExample.java View source code
public void example2Errors() {
    Observable<Long> failAt200 = Observable.concat(Observable.interval(100, TimeUnit.MILLISECONDS).take(2), Observable.error(new Exception("Failed")));
    Observable<Long> failAt300 = Observable.concat(Observable.interval(100, TimeUnit.MILLISECONDS).take(3), Observable.error(new Exception("Failed")));
    Observable<Long> completeAt400 = Observable.interval(100, TimeUnit.MILLISECONDS).take(4);
    Observable.mergeDelayError(failAt200, failAt300, completeAt400).subscribe(System.out::println, System.out::println);
// 0
// 0
// 0
// 1
// 1
// 1
// 2
// 2
// 3
// rx.exceptions.CompositeException: 2 exceptions occurred. 
}
Example 3
Project: zava-master  File: AbstractOnSubscribe.java View source code
/**
         * Emits the {@code onNext} and/or the terminal value to the actual subscriber.
         *
         * @return {@code true} if the event was a terminal event
         */
protected boolean accept() {
    if (hasOnNext) {
        T value = theValue;
        theValue = null;
        hasOnNext = false;
        try {
            subscriber.onNext(value);
        } catch (Throwable t) {
            hasCompleted = true;
            Throwable e = theException;
            theException = null;
            if (e == null) {
                subscriber.onError(t);
            } else {
                subscriber.onError(new CompositeException(Arrays.asList(t, e)));
            }
            return true;
        }
    }
    if (hasCompleted) {
        Throwable e = theException;
        theException = null;
        if (e != null) {
            subscriber.onError(e);
        } else {
            subscriber.onCompleted();
        }
        return true;
    }
    return false;
}
Example 4
Project: org.openntf.domino-master  File: OperatorMerge.java View source code
private void drainAndComplete() {
    // TODO need to confirm whether this is needed or not
    drainQueuesIfNeeded();
    if (delayErrors) {
        Queue<Throwable> es = null;
        synchronized (this) {
            es = exceptions;
        }
        if (es != null) {
            if (es.isEmpty()) {
                actual.onCompleted();
            } else if (es.size() == 1) {
                actual.onError(es.poll());
            } else {
                actual.onError(new CompositeException(es));
            }
        } else {
            actual.onCompleted();
        }
    } else {
        actual.onCompleted();
    }
}
Example 5
Project: azure-sdk-for-java-master  File: LoadBalancerImpl.java View source code
@Override
protected void afterCreating() {
    List<Exception> nicExceptions = new ArrayList<>();
    // Update the NICs to point to the backend pool
    for (Entry<String, String> nicInBackend : this.nicsInBackends.entrySet()) {
        String nicId = nicInBackend.getKey();
        String backendName = nicInBackend.getValue();
        try {
            NetworkInterface nic = this.manager().networkInterfaces().getById(nicId);
            NicIPConfiguration nicIP = nic.primaryIPConfiguration();
            nic.update().updateIPConfiguration(nicIP.name()).withExistingLoadBalancerBackend(this, backendName).parent().apply();
        } catch (Exception e) {
            nicExceptions.add(e);
        }
    }
    if (!nicExceptions.isEmpty()) {
        throw new CompositeException(nicExceptions);
    }
    this.nicsInBackends.clear();
    this.refresh();
}
Example 6
Project: couchbase-java-client-master  File: N1qlQueryExecutor.java View source code
@Override
public Observable<PreparedPayload> call(GenericQueryResponse r) {
    if (r.status().isSuccess()) {
        r.info().subscribe(Buffers.BYTE_BUF_RELEASER);
        r.signature().subscribe(Buffers.BYTE_BUF_RELEASER);
        r.errors().subscribe(Buffers.BYTE_BUF_RELEASER);
        r.profileInfo().subscribe(Buffers.BYTE_BUF_RELEASER);
        return r.rows().map(new Func1<ByteBuf, PreparedPayload>() {

            @Override
            public PreparedPayload call(ByteBuf byteBuf) {
                try {
                    JsonObject value = JSON_OBJECT_TRANSCODER.byteBufToJsonObject(byteBuf);
                    return extractPreparedPayloadFromResponse(prepared, value);
                } catch (Exception e) {
                    throw new TranscodingException("Could not decode N1QL Query Plan.", e);
                } finally {
                    byteBuf.release();
                }
            }
        });
    } else {
        r.info().subscribe(Buffers.BYTE_BUF_RELEASER);
        r.signature().subscribe(Buffers.BYTE_BUF_RELEASER);
        r.rows().subscribe(Buffers.BYTE_BUF_RELEASER);
        r.profileInfo().subscribe(Buffers.BYTE_BUF_RELEASER);
        return r.errors().map(new Func1<ByteBuf, Exception>() {

            @Override
            public Exception call(ByteBuf byteBuf) {
                try {
                    JsonObject value = JSON_OBJECT_TRANSCODER.byteBufToJsonObject(byteBuf);
                    return new CouchbaseException("N1qlQuery Error - " + value.toString());
                } catch (Exception e) {
                    throw new TranscodingException("Could not decode N1QL Query Plan.", e);
                } finally {
                    byteBuf.release();
                }
            }
        }).reduce(new ArrayList<Throwable>(), new Func2<ArrayList<Throwable>, Exception, ArrayList<Throwable>>() {

            @Override
            public ArrayList<Throwable> call(ArrayList<Throwable> throwables, Exception error) {
                throwables.add(error);
                return throwables;
            }
        }).flatMap(new Func1<ArrayList<Throwable>, Observable<PreparedPayload>>() {

            @Override
            public Observable<PreparedPayload> call(ArrayList<Throwable> errors) {
                if (errors.size() == 1) {
                    return Observable.error(new CouchbaseException("Error while preparing plan", errors.get(0)));
                } else {
                    return Observable.error(new CompositeException("Multiple errors while preparing plan", errors));
                }
            }
        });
    }
}
Example 7
Project: servo-master  File: HttpHelper.java View source code
private void logErr(String prefix, Throwable e, int sent, int total) {
    if (LOGGER.isWarnEnabled()) {
        final Throwable cause = e.getCause() != null ? e.getCause() : e;
        String msg = String.format("%s exception %s:%s Sent %d/%d", prefix, cause.getClass().getSimpleName(), cause.getMessage(), sent, total);
        LOGGER.warn(msg);
        if (cause instanceof CompositeException) {
            CompositeException ce = (CompositeException) cause;
            for (Throwable t : ce.getExceptions()) {
                LOGGER.warn(" Exception {}: {}", t.getClass().getSimpleName(), t.getMessage());
            }
        }
    }
}
Example 8
Project: async-http-client-master  File: AsyncHttpSingleTest.java View source code
@Test(groups = "standalone")
public void testErrorInOnThrowablePropagation() throws Exception {
    final RuntimeException processingException = new RuntimeException("processing");
    final RuntimeException thrownException = new RuntimeException("thrown");
    @SuppressWarnings("unchecked") final AsyncHandler<Object> handler = mock(AsyncHandler.class);
    doThrow(thrownException).when(handler).onThrowable(processingException);
    final Single<?> underTest = AsyncHttpSingle.create( bridge -> {
        try {
            bridge.onThrowable(processingException);
            return mock(Future.class);
        } catch (final Throwable t) {
            throw new AssertionError(t);
        }
    }, () -> handler);
    final TestSubscriber<Object> subscriber = new TestSubscriber<>();
    underTest.subscribe(subscriber);
    verify(handler).onThrowable(processingException);
    verifyNoMoreInteractions(handler);
    subscriber.awaitTerminalEvent();
    subscriber.assertTerminalEvent();
    subscriber.assertNoValues();
    final List<Throwable> errorEvents = subscriber.getOnErrorEvents();
    assertEquals(errorEvents.size(), 1);
    assertThat(errorEvents.get(0), is(instanceOf(CompositeException.class)));
    final CompositeException error = (CompositeException) errorEvents.get(0);
    assertEquals(error.getExceptions(), Arrays.asList(processingException, thrownException));
}
Example 9
Project: nextop-client-master  File: RxExceptionTest.java View source code
public void testExceptionSubjectObserverCustomThrow() {
    // setup:
    // subject -> observer
    // shows that an exception in observer#onNext will call observer#onError,
    // and that an unahndled exception in observer#onError will come back to the caller
    BehaviorSubject<Integer> subject = BehaviorSubject.create();
    final List<Notification<Integer>> notifications = new ArrayList<Notification<Integer>>(4);
    Subscription s = subject.subscribe(new Observer<Integer>() {

        @Override
        public void onNext(Integer t) {
            notifications.add(Notification.createOnNext(t));
            throw new RuntimeException("onNext " + t);
        }

        @Override
        public void onCompleted() {
            notifications.add(Notification.<Integer>createOnCompleted());
        }

        @Override
        public void onError(Throwable e) {
            notifications.add(Notification.<Integer>createOnError(e));
            if (e instanceof RuntimeException) {
                // TODO assume an error path from onNext
                throw (RuntimeException) e;
            } else if (e instanceof Error) {
                // TODO assume an error path from onNext
                throw (Error) e;
            } else {
            // TODO
            // a normal error path?
            }
        }
    });
    try {
        subject.onNext(0);
        // (unreachable) expect an exception to be thrown
        fail();
    } catch (RuntimeException e) {
        assertTrue(e instanceof OnErrorFailedException);
        assertTrue(e.getCause() instanceof CompositeException);
        assertEquals("onNext 0", e.getCause().getCause().getCause().getMessage());
    }
}
Example 10
Project: rxjava-gwt-master  File: TestSubscriber.java View source code
/**
     * Asserts that there is exactly one error event which is a subclass of the given class.
     *
     * @param clazz the class to check the error against.
     * @throws AssertionError if there were zero, or more than one, onError events, or if the single onError
     *                        event did not carry an error of a subclass of the given class
     * @since 1.1.0
     */
@GwtIncompatible
public void assertError(Class<? extends Throwable> clazz) {
    List<Throwable> err = errors;
    if (err.isEmpty()) {
        assertionError("No errors");
    } else if (err.size() > 1) {
        AssertionError ae = new AssertionError("Multiple errors: " + err.size());
        ae.initCause(new CompositeException(err));
        throw ae;
    } else if (!clazz.isInstance(err.get(0))) {
        AssertionError ae = new AssertionError("Exceptions differ; expected: " + clazz + ", actual: " + err.get(0));
        ae.initCause(err.get(0));
        throw ae;
    }
}
Example 11
Project: rx-java-extensions-master  File: OperatorSwitchThenUnsubscribe.java View source code
boolean updateError(Throwable next) {
    Throwable e = error;
    if (e == TERMINAL_ERROR) {
        return false;
    } else if (e == null) {
        error = next;
    } else if (e instanceof CompositeException) {
        List<Throwable> list = new ArrayList<Throwable>(((CompositeException) e).getExceptions());
        list.add(next);
        error = new CompositeException(list);
    } else {
        error = new CompositeException(e, next);
    }
    return true;
}
Example 12
Project: sfs-master  File: JournalFile.java View source code
public Observable<Void> open(SfsVertx vertx) {
    return aVoid().flatMap( aVoid -> {
        BlobFile internalBlobFile = new BlobFile(path, SUPER_BLOCK_SIZE, DEFAULT_WRITE_STREAM_TIMEOUT);
        return internalBlobFile.open(vertx, CREATE_NEW, READ, WRITE).flatMap( aVoid1 -> internalBlobFile.enableWrites(vertx)).flatMap( aVoid1 -> {
            Super superBlock = newBuilder().setBlockSize(DEFAULT_BLOCK_SIZE).build();
            return setSuperBlock(vertx, internalBlobFile, superBlock).map( aVoid11 -> superBlock);
        }).onErrorResumeNext( throwable -> {
            if (containsException(FileAlreadyExistsException.class, throwable)) {
                return internalBlobFile.close(vertx).flatMap( aVoid1 -> internalBlobFile.open(vertx, CREATE, READ, WRITE)).flatMap( aVoid1 -> internalBlobFile.enableWrites(vertx)).flatMap( aVoid1 -> getSuperBlock(vertx, internalBlobFile));
            } else {
                return error(throwable);
            }
        }).doOnNext( superBlock -> {
            blockSize = superBlock.getBlockSize();
            logStartPosition = up(SUPER_BLOCK_RESERVED, blockSize);
        }).map(new ToVoid<>()).flatMap( aVoid1 -> internalBlobFile.disableWrites(vertx)).flatMap( aVoid1 -> internalBlobFile.force(vertx, true)).onErrorResumeNext( throwable -> {
            if (!STOPPED.equals(blobFile.getStatus())) {
                return internalBlobFile.close(vertx).onErrorResumeNext( throwable1 -> {
                    return error(new CompositeException(throwable, throwable1));
                });
            } else {
                return error(throwable);
            }
        }).flatMap( aVoid1 -> internalBlobFile.close(vertx));
    }).flatMap( aVoid -> {
        blobFile = new BlobFile(path, blockSize, DEFAULT_WRITE_STREAM_TIMEOUT);
        return blobFile.open(vertx, CREATE, READ, WRITE);
    });
}
Example 13
Project: RxJavaParallel-master  File: OperatorParallelMerge.java View source code
private void drainAndComplete() {
    // TODO need to confirm whether this is needed or not
    drainQueuesIfNeeded();
    if (delayErrors) {
        Queue<Throwable> es = null;
        synchronized (this) {
            es = exceptions;
        }
        if (es != null) {
            if (es.isEmpty()) {
                actual.onCompleted();
            } else if (es.size() == 1) {
                actual.onError(es.poll());
            } else {
                actual.onError(new CompositeException(es));
            }
        } else {
            actual.onCompleted();
        }
    } else {
        actual.onCompleted();
    }
}
Example 14
Project: rxjava-extras-master  File: OrderedMerge.java View source code
void reportErrorOrComplete(Subscriber<? super T> child) {
    if (delayErrors && !errors.isEmpty()) {
        if (errors.size() == 1) {
            child.onError(errors.poll());
        } else {
            child.onError(new CompositeException(errors));
        }
    } else {
        child.onCompleted();
    }
}
Example 15
Project: hawkular-metrics-master  File: SortedMerge.java View source code
protected void reportErrorOrComplete(Subscriber<? super T> child) {
    if (delayErrors && !errors.isEmpty()) {
        if (errors.size() == 1) {
            child.onError(errors.poll());
        } else {
            child.onError(new CompositeException(errors));
        }
    } else {
        child.onCompleted();
    }
}