reactor.core.Exceptions Java Examples

The following examples show how to use reactor.core.Exceptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MonoDoFinallyTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void callbackThrows() {
	try {
		StepVerifier.create(Mono.just(1)
		                        .doFinally(signal -> {
			                        throw new IllegalStateException();
		                        }))
		            .expectNext(1)
		            .expectComplete()
		            .verify();
	}
	catch (Throwable e) {
		Throwable _e = Exceptions.unwrap(e);
		assertNotSame(e, _e);
		assertThat(_e).isInstanceOf(IllegalStateException.class);
	}
}
 
Example #2
Source File: FluxCombineLatest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
boolean checkTerminated(boolean d, boolean empty, Queue<SourceAndArray> q) {
	if (cancelled) {
		cancelAll();
		discardQueue(q);
		return true;
	}

	if (d) {
		Throwable e = Exceptions.terminate(ERROR, this);

		if (e != null && e != Exceptions.TERMINATED) {
			cancelAll();
			discardQueue(q);
			actual.onError(e);
			return true;
		}
		else if (empty) {
			cancelAll();

			actual.onComplete();
			return true;
		}
	}
	return false;
}
 
Example #3
Source File: FluxCreateTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
void fluxCreateErrorBackpressured() {
	Flux<String> created = Flux.create(s -> {
		assertThat(s.requestedFromDownstream()).isEqualTo(1);
		s.next("test1");
		s.next("test2");
		s.next("test3");
		s.complete();
	}, FluxSink.OverflowStrategy.ERROR);

	StepVerifier.create(created, 1)
	            .expectNext("test1")
	            .thenAwait()
	            .thenRequest(2)
	            .verifyErrorMatches(Exceptions::isOverflow);
}
 
Example #4
Source File: ErrorHandlingTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testUsingMethod() {
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    Closeable closable = () -> System.out.println("closing the stream");
    Flux.using(() -> closable, x -> fibonacciGenerator, e -> {
        try {
            e.close();
        } catch (Exception e1) {
            throw Exceptions.propagate(e1);
        }
    }).subscribe(System.out::println);
}
 
Example #5
Source File: FluxBufferWhen.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
void boundaryError(Disposable boundary, Throwable ex) {
	Operators.terminate(S, this);
	subscribers.remove(boundary);
	if (Exceptions.addThrowable(ERRORS, this, ex)) {
		subscribers.dispose();
		Map<Long, BUFFER> bufs;
		synchronized (this) {
			bufs = buffers;
			buffers = null;
		}
		done = true;
		drain();
		if (bufs != null) {
			for (BUFFER buffer : bufs.values()) {
				Operators.onDiscardMultiple(buffer, this.ctx);
			}
		}
	}
	else {
		Operators.onErrorDropped(ex, this.ctx);
	}
}
 
Example #6
Source File: OnNextFailureStrategyTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void resumeDropDoesntSelfSuppressIfHookRethrows() {
	AtomicReference<Object> value = new AtomicReference<>();
	Hooks.onErrorDropped(e -> { throw Exceptions.propagate(e); });
	Hooks.onNextDropped(value::set);

	OnNextFailureStrategy strategy = OnNextFailureStrategy.resumeDrop();

	String data = "foo";
	Throwable exception = new IllegalArgumentException("foo");

	assertThat(strategy.test(exception, data)).as("predicate matches").isTrue();
	Throwable t = strategy.process(exception, data, Context.empty());

	assertThat(t)
			.isSameAs(exception)
			.hasNoSuppressedExceptions();
	assertThat(value.get()).isEqualTo("foo");
}
 
Example #7
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
boolean onSignal(Signal<T> actualSignal) {
	SignalEvent<T> signalEvent = (SignalEvent<T>) this.script.poll();
	Optional<AssertionError> error = signalEvent.test(actualSignal);
	if (error.isPresent()) {
		Exceptions.addThrowable(ERRORS, this, error.get());
		// #55 ensure the onError is added as a suppressed to the AssertionError
		if(actualSignal.isOnError()) {
			error.get().addSuppressed(actualSignal.getThrowable());
		}
		maybeCancel(actualSignal);
		this.completeLatch.countDown();
		return true;
	}
	if (actualSignal.isOnNext()) {
		unasserted--;
	}
	return false;
}
 
Example #8
Source File: LambdaSubscriber.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public final void onSubscribe(Subscription s) {
	if (Operators.validate(subscription, s)) {
		this.subscription = s;
		if (subscriptionConsumer != null) {
			try {
				subscriptionConsumer.accept(s);
			}
			catch (Throwable t) {
				Exceptions.throwIfFatal(t);
				s.cancel();
				onError(t);
			}
		}
		else {
			s.request(Long.MAX_VALUE);
		}
	}
}
 
Example #9
Source File: FluxBufferTimeout.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
void nextCallback(T value) {
	synchronized (this) {
		if (OUTSTANDING.decrementAndGet(this) < 0)
		{
			actual.onError(Exceptions.failWithOverflow("Unrequested element received"));
			Context ctx = actual.currentContext();
			Operators.onDiscard(value, ctx);
			Operators.onDiscardMultiple(values, ctx);
			return;
		}

		C v = values;
		if(v == null) {
			v = Objects.requireNonNull(bufferSupplier.get(),
					"The bufferSupplier returned a null buffer");
			values = v;
		}
		v.add(value);
	}
}
 
Example #10
Source File: OnNextFailureStrategy.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public Throwable process(Throwable error, @Nullable Object value, Context context) {
	if (errorPredicate == null) {
		Exceptions.throwIfFatal(error);
	}
	else if (!errorPredicate.test(error)) {
		Exceptions.throwIfFatal(error);
		return error;
	}
	try {
		errorConsumer.accept(error, value);
		return null;
	}
	catch (Throwable e) {
		return Exceptions.addSuppressed(e, error);
	}
}
 
Example #11
Source File: FluxPublishOn.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(T t) {
	if (sourceMode == ASYNC) {
		trySchedule(this, null, null /* t always null */);
		return;
	}

	if (done) {
		Operators.onNextDropped(t, actual.currentContext());
		return;
	}

	if (cancelled) {
		Operators.onDiscard(t, actual.currentContext());
		return;
	}

	if (!queue.offer(t)) {
		Operators.onDiscard(t, actual.currentContext());
		error = Operators.onOperatorError(s, Exceptions.failWithOverflow(Exceptions.BACKPRESSURE_ERROR_QUEUE_FULL), t,
				actual.currentContext());
		done = true;
	}
	trySchedule(this, null, t);
}
 
Example #12
Source File: FluxUsing.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public void onError(Throwable t) {
	if (eager && WIP.compareAndSet(this, 0, 1)) {
		try {
			resourceCleanup.accept(resource);
		}
		catch (Throwable e) {
			Throwable _e = Operators.onOperatorError(e, actual.currentContext());
			t = Exceptions.addSuppressed(_e, t);
		}
	}

	actual.onError(t);

	if (!eager && WIP.compareAndSet(this, 0, 1)) {
		cleanup();
	}
}
 
Example #13
Source File: DelegateServiceSchedulerTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void notScheduledRejects() {
	Scheduler s = afterTest.autoDispose(Schedulers.fromExecutorService(Executors.newSingleThreadExecutor()));
	assertThatExceptionOfType(RejectedExecutionException.class)
			.isThrownBy(() -> s.schedule(() -> {}, 100, TimeUnit.MILLISECONDS))
			.describedAs("direct delayed scheduling")
			.isSameAs(Exceptions.failWithRejectedNotTimeCapable());
	assertThatExceptionOfType(RejectedExecutionException.class)
			.isThrownBy(() -> s.schedulePeriodically(() -> {}, 100, 100, TimeUnit.MILLISECONDS))
			.describedAs("direct periodic scheduling")
			.isSameAs(Exceptions.failWithRejectedNotTimeCapable());

	Worker w = afterTest.autoDispose(s.createWorker());
	assertThatExceptionOfType(RejectedExecutionException.class)
			.isThrownBy(() -> w.schedule(() -> {}, 100, TimeUnit.MILLISECONDS))
			.describedAs("worker delayed scheduling")
			.isSameAs(Exceptions.failWithRejectedNotTimeCapable());
	assertThatExceptionOfType(RejectedExecutionException.class)
			.isThrownBy(() -> w.schedulePeriodically(() -> {}, 100, 100, TimeUnit.MILLISECONDS))
			.describedAs("worker periodic scheduling")
			.isSameAs(Exceptions.failWithRejectedNotTimeCapable());
}
 
Example #14
Source File: ExecutorScheduler.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public Disposable schedule(Runnable task) {
	Objects.requireNonNull(task, "task");

	ExecutorTrackedRunnable r = new ExecutorTrackedRunnable(task, this, true);
	if (!tasks.add(r)) {
		throw Exceptions.failWithRejected();
	}

	try {
		executor.execute(r);
	}
	catch (Throwable ex) {
		tasks.remove(r);
		Schedulers.handleError(ex);
		throw Exceptions.failWithRejected(ex);
	}

	return r;
}
 
Example #15
Source File: FluxFlatMapTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test //FIXME use Violation.NO_CLEANUP_ON_TERMINATE
public void failDoubleErrorTerminatedInner() {
	try {
		StepVerifier.create(Flux.just(1).hide().flatMap(f -> Flux.from(s -> {
			s.onSubscribe(Operators.emptySubscription());
			Exceptions.terminate(FluxFlatMap.FlatMapMain.ERROR,( (FluxFlatMap
					.FlatMapInner) s).parent);
			s.onError(new Exception("test"));
		})))
		            .verifyErrorMessage("test");
		Assert.fail();
	}
	catch (Exception e) {
		assertThat(Exceptions.unwrap(e)).hasMessage("test");
	}
}
 
Example #16
Source File: FluxOnBackpressureBufferTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void onBackpressureBufferMaxCallbackSourceEmitsAfterComplete() {
	TestPublisher<Integer> testPublisher = TestPublisher.createNoncompliant(TestPublisher.Violation.DEFER_CANCELLATION);
	CopyOnWriteArrayList<Integer> overflown = new CopyOnWriteArrayList<>();
	AtomicInteger producedCounter = new AtomicInteger();

	StepVerifier.create(testPublisher.flux()
	                                 .doOnNext(i -> producedCounter.incrementAndGet())
	                                 .onBackpressureBuffer(3, overflown::add),
			StepVerifierOptions.create().initialRequest(0).checkUnderRequesting(false))
	            .thenRequest(5)
				.then(() -> testPublisher.next(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15))
	            .expectNext(1, 2, 3, 4, 5)
	            .thenAwait() //at this point the buffer is overrun since the range request was unbounded
	            .thenRequest(100) //requesting more empties the buffer before an overflow error is propagated
	            .expectNext(6, 7, 8)
	            .expectErrorMatches(Exceptions::isOverflow)
	            .verifyThenAssertThat()
	            .hasDroppedExactly(10, 11, 12, 13, 14, 15);

	//the rest, asserted above, is dropped because the source was cancelled
	assertThat(overflown).as("passed to overflow handler").containsExactly(9);
	assertThat(producedCounter).as("bad source produced").hasValue(15);
}
 
Example #17
Source File: MonoUsing.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public void onError(Throwable t) {
	if (valued && mode != ASYNC) {
		Operators.onErrorDropped(t, actual.currentContext());
		return;
	}
	if (eager && WIP.compareAndSet(this, 0, 1)) {
		try {
			resourceCleanup.accept(resource);
		}
		catch (Throwable e) {
			Throwable _e = Operators.onOperatorError(e, actual.currentContext());
			t = Exceptions.addSuppressed(_e, t);
		}
	}

	actual.onError(t);

	if (!eager && WIP.compareAndSet(this, 0, 1)) {
		cleanup();
	}
}
 
Example #18
Source File: MonoProcessor.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value that completed this {@link MonoProcessor}. Returns {@code null} if the {@link MonoProcessor} has not been completed. If the
 * {@link MonoProcessor} is completed with an error a RuntimeException that wraps the error is thrown.
 *
 * @return the value that completed the {@link MonoProcessor}, or {@code null} if it has not been completed
 *
 * @throws RuntimeException if the {@link MonoProcessor} was completed with an error
 */
@Nullable
public O peek() {
	if (!isTerminated()) {
		return null;
	}

	if (value != null) {
		return value;
	}

	if (error != null) {
		RuntimeException re = Exceptions.propagate(error);
		re = Exceptions.addSuppressed(re, new Exception("Mono#peek terminated with an error"));
		throw re;
	}

	return null;
}
 
Example #19
Source File: FluxCreate.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public void error(Throwable t) {
	Objects.requireNonNull(t, "t is null in sink.error(t)");
	if (sink.isTerminated() || done) {
		Operators.onOperatorError(t, sink.currentContext());
		return;
	}
	if (Exceptions.addThrowable(ERROR, this, t)) {
		done = true;
		drain();
	}
	else {
		Context ctx = sink.currentContext();
		Operators.onDiscardQueueWithClear(mpscQueue, ctx, null);
		Operators.onOperatorError(t, ctx);
	}
}
 
Example #20
Source File: FluxUsing.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public void onError(Throwable t) {
	if (eager && WIP.compareAndSet(this, 0, 1)) {
		try {
			resourceCleanup.accept(resource);
		}
		catch (Throwable e) {
			Throwable _e = Operators.onOperatorError(e, actual.currentContext());
			t = Exceptions.addSuppressed(_e, t);
		}
	}

	actual.onError(t);

	if (!eager && WIP.compareAndSet(this, 0, 1)) {
		cleanup();
	}
}
 
Example #21
Source File: FluxConcatMap.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public void innerError(Throwable e) {
	e = Operators.onNextInnerError(e, currentContext(), s);
	if(e != null) {
		if (Exceptions.addThrowable(ERROR, this, e)) {
			if (!veryEnd) {
				s.cancel();
				done = true;
			}
			active = false;
			drain();
		}
		else {
			Operators.onErrorDropped(e, actual.currentContext());
		}
	}
	else {
		active = false;
	}
}
 
Example #22
Source File: FluxOnBackpressureBufferTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void onBackpressureBufferMaxCallbackUnder8() {
	CopyOnWriteArrayList<Integer> overflown = new CopyOnWriteArrayList<>();
	AtomicInteger producedCounter = new AtomicInteger();

	StepVerifier.create(Flux.range(1, 15)
	                        .doOnNext(i -> producedCounter.incrementAndGet())
	                        .hide()
	                        .onBackpressureBuffer(3, overflown::add),
			StepVerifierOptions.create().initialRequest(0).checkUnderRequesting(false))
	            .thenRequest(5)
	            .expectNext(1, 2, 3, 4, 5)
	            .thenAwait() //at this point the buffer is overrun since the range request was unbounded
	            .thenRequest(100) //requesting more empties the buffer before an overflow error is propagated
	            .expectNext(6, 7, 8)
	            .expectErrorMatches(Exceptions::isOverflow)
	            .verifyThenAssertThat()
	            .hasNotDroppedElements();

	assertThat(overflown).as("passed to overflow handler").containsExactly(9);
	assertThat(producedCounter).as("good source cancelled on first overflow").hasValue(9);
}
 
Example #23
Source File: BlockingTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void blockingLastInterrupted() throws Exception {
	CountDownLatch latch = new CountDownLatch(1);
	Thread t = new Thread(() -> {
		try {
			Flux.never()
			    .blockLast();
		}
		catch (Exception e) {
			if (Exceptions.unwrap(e) instanceof InterruptedException) {
				latch.countDown();
			}
		}
	});

	t.start();
	Thread.sleep(1000);
	t.interrupt();

	Assert.assertTrue("Not interrupted ?", latch.await(3, TimeUnit.SECONDS));
}
 
Example #24
Source File: DefaultHttpServerRoutes.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
public Publisher<Void> apply(HttpServerRequest request, HttpServerResponse response) {
	final Iterator<HttpRouteHandler> iterator = handlers.iterator();
	HttpRouteHandler cursor;

	try {
		while (iterator.hasNext()) {
			cursor = iterator.next();
			if (cursor.test(request)) {
				return cursor.apply(request, response);
			}
		}
	}
	catch (Throwable t) {
		Exceptions.throwIfJvmFatal(t);
		return Mono.error(t); //500
	}

	return response.sendNotFound();
}
 
Example #25
Source File: FluxFlatMapTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void failOverflowWhileActiveScalarThenError() {
	AtomicBoolean set = new AtomicBoolean();
	Hooks.onErrorDropped(e -> {
		assertThat(Exceptions.isOverflow(e)).isTrue();
		set.set(true);
	});
	StepVerifier.create(Flux.from(s -> {
		s.onSubscribe(Operators.emptySubscription());
		s.onNext(1);
		Exceptions.terminate(FluxFlatMap.FlatMapMain.ERROR, (FluxFlatMap.FlatMapMain) s);
		((FluxFlatMap.FlatMapMain)s).wip = 1; //simulate concurrent active
		s.onNext(2);
		s.onNext(3);
		((FluxFlatMap.FlatMapMain)s).error = null;
		((FluxFlatMap.FlatMapMain)s).drainLoop();
		s.onError(new Exception("test"));
	})
	                        .flatMap(Flux::just, 1), 1)
	            .expectNext(1)
	            .verifyErrorMessage("test");
	assertThat(set.get()).isTrue();
}
 
Example #26
Source File: FluxSwitchMap.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
boolean checkTerminated(boolean d, boolean empty, Subscriber<?> a, Queue<?> q) {
	if (cancelled) {
		cancelAndCleanup(q);
		return true;
	}

	if (d) {
		Throwable e = Exceptions.terminate(ERROR, this);
		if (e != null && e != Exceptions.TERMINATED) {
			cancelAndCleanup(q);

			a.onError(e);
			return true;
		}
		else if (empty) {
			a.onComplete();
			return true;
		}

	}
	return false;
}
 
Example #27
Source File: NettyOutbound.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
/**
 * Sends content from the given {@link Path} using
 * {@link java.nio.channels.FileChannel#transferTo(long, long, WritableByteChannel)}
 * support, if the system supports it, the path resolves to a local file
 * system {@link File}, compression and SSL/TLS is not enabled, then transfer will
 * use zero-byte copy to the peer., otherwise chunked read/write will be used.
 * <p>It will listens for any error on write and closes
 * on terminal signal (complete|error). If more than one publisher is attached
 * (multiple calls to send()) completion occurs after all publishers complete.</p>
 * <p></p>Note: Nesting any send* method is not supported.</p>
 *
 * @param file the file Path
 * @param position where to start
 * @param count how much to transfer
 *
 * @return A Publisher to signal successful sequence write (e.g. after "flush") or any
 * error during write
 */
default NettyOutbound sendFile(Path file, long position, long count) {
	Objects.requireNonNull(file, "filepath");

	return sendUsing(() -> FileChannel.open(file, StandardOpenOption.READ),
			(c, fc) -> {
				if (ReactorNetty.mustChunkFileTransfer(c, file)) {
					ReactorNetty.addChunkedWriter(c);
					try {
						return new ChunkedNioFile(fc, position, count, 1024);
					}
					catch (Exception ioe) {
						throw Exceptions.propagate(ioe);
					}
				}
				return new DefaultFileRegion(fc, position, count);
			},
			ReactorNetty.fileCloser);
}
 
Example #28
Source File: FluxDoFinallyTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void callbackThrows() {
	try {
		StepVerifier.create(Flux.just(1)
		                        .doFinally(signal -> {
			                        throw new IllegalStateException();
		                        }))
		            .expectNext(1)
		            .expectComplete()
		            .verify();
	}
	catch (Throwable e) {
		Throwable _e = Exceptions.unwrap(e);
		assertNotSame(e, _e);
		assertThat(_e).isInstanceOf(IllegalStateException.class);
	}
}
 
Example #29
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
public void monoRetryFixedBackoff() {
  Mono<?> mono =
      Mono.error(new IOException())
          .retryWhen(Retry.fixedDelay(1, Duration.ofMillis(500)).doAfterRetry(onRetry()))
          .as(m -> new ReconnectMono<>(m, onExpire(), onValue()));

  StepVerifier.withVirtualTime(() -> mono)
      .expectSubscription()
      .expectNoEvent(Duration.ofMillis(300))
      .thenAwait(Duration.ofMillis(300))
      .verifyErrorMatches(Exceptions::isRetryExhausted);

  assertRetries(IOException.class);

  Assertions.assertThat(received).isEmpty();
  Assertions.assertThat(expired).isEmpty();
}
 
Example #30
Source File: RetryBackoffSpecTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void backoffSchedulerDefaultIsLazilyResolved() {
	RetryBackoffSpec spec = Retry.backoff(3, Duration.ofMillis(10));

	StepVerifier.withVirtualTime(() -> Flux.error(new IllegalStateException("boom"))
	                                       .retryWhen(spec)
	)
	            .expectSubscription()
	            .thenAwait(Duration.ofHours(1))
	            .expectErrorMatches(Exceptions::isRetryExhausted)
	            .verify(Duration.ofSeconds(1));
}