Java Code Examples for reactor.core.Exceptions#unwrap()

The following examples show how to use reactor.core.Exceptions#unwrap() . 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: MonoPeekAfterTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void afterTerminateCallbackFailureInterruptsOnNextAndThrows() {
	LongAdder invoked = new LongAdder();
	try {
		StepVerifier.create(Mono.just("foo")
		                        .doAfterTerminate(() -> {
			                        invoked.increment();
			                        throw new IllegalArgumentException("boom");
		                        }))
		            .expectNext("bar") //irrelevant
		            .expectErrorMessage("baz") //irrelevant
		            .verify();
	}
	catch (Throwable t) {
		Throwable e = Exceptions.unwrap(t);
		assertEquals(IllegalArgumentException.class, e.getClass());
		assertEquals("boom", e.getMessage());
	}

	assertEquals(1, invoked.intValue());
}
 
Example 2
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 3
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 4
Source File: MonoDoFinallyTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void callbackThrowsConditional() {
	try {
		StepVerifier.create(Mono.just(1)
		                        .doFinally(signal -> {
			                        throw new IllegalStateException();
		                        })
		                        .filter(i -> true))
		            .expectNext(1)
		            .expectComplete()
		            .verify();
	}
	catch (Throwable e) {
		Throwable _e = Exceptions.unwrap(e);
		assertNotSame(e, _e);
		assertThat(_e).isInstanceOf(IllegalStateException.class);
	}
}
 
Example 5
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 6
Source File: FluxDoFinallyTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void callbackThrowsConditional() {
	try {
		StepVerifier.create(Flux.just(1)
		                        .doFinally(signal -> {
			                        throw new IllegalStateException();
		                        })
		                        .filter(i -> true))
		            .expectNext(1)
		            .expectComplete()
		            .verify();
	}
	catch (Throwable e) {
		Throwable _e = Exceptions.unwrap(e);
		assertNotSame(e, _e);
		assertThat(_e).isInstanceOf(IllegalStateException.class);
	}
}
 
Example 7
Source File: CosmosDBExceptionUtils.java    From spring-data-cosmosdb with MIT License 5 votes vote down vote up
public static <T> Mono<T> exceptionHandler(String message, Throwable throwable) {
    if (StringUtils.isEmpty(message)) {
        message = "Failed to access cosmosdb database";
    }
    //  Unwrap the exception in case if it is a reactive exception
    final Throwable unwrappedThrowable = Exceptions.unwrap(throwable);
    throw new CosmosDBAccessException(message, unwrappedThrowable);
}
 
Example 8
Source File: CosmosDBExceptionUtils.java    From spring-data-cosmosdb with MIT License 5 votes vote down vote up
public static <T> Mono<T> findAPIExceptionHandler(String message, Throwable throwable) {
    //  Unwrap the exception in case if it is a reactive exception
    final Throwable unwrappedThrowable = Exceptions.unwrap(throwable);
    if (unwrappedThrowable instanceof CosmosClientException) {
        final CosmosClientException cosmosClientException = (CosmosClientException) unwrappedThrowable;
        if (cosmosClientException.statusCode() == HttpConstants.StatusCodes.NOTFOUND) {
            return Mono.empty();
        }
    }
    return exceptionHandler(message, unwrappedThrowable);
}
 
Example 9
Source File: Operators.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
/**
 * Map an "operator" error given an operator parent {@link Subscription}. The
 * result error will be passed via onError to the operator downstream.
 * {@link Subscription} will be cancelled after checking for fatal error via
 * {@link Exceptions#throwIfFatal(Throwable)}. Takes an additional signal, which
 * can be added as a suppressed exception if it is a {@link Throwable} and the
 * default {@link Hooks#onOperatorError(BiFunction) hook} is in place.
 *
 * @param subscription the linked operator parent {@link Subscription}
 * @param error the callback or operator error
 * @param dataSignal the value (onNext or onError) signal processed during failure
 * @param context a context that might hold a local error consumer
 * @return mapped {@link Throwable}
 *
 */
public static Throwable onOperatorError(@Nullable Subscription subscription,
		Throwable error,
		@Nullable Object dataSignal, Context context) {

	Exceptions.throwIfFatal(error);
	if(subscription != null) {
		subscription.cancel();
	}

	Throwable t = Exceptions.unwrap(error);
	BiFunction<? super Throwable, Object, ? extends Throwable> hook =
			context.getOrDefault(Hooks.KEY_ON_OPERATOR_ERROR, null);
	if (hook == null) {
		hook = Hooks.onOperatorErrorHook;
	}
	if (hook == null) {
		if (dataSignal != null) {
			if (dataSignal != t && dataSignal instanceof Throwable) {
				t = Exceptions.addSuppressed(t, (Throwable) dataSignal);
			}
			//do not wrap original value to avoid strong references
			/*else {
			}*/
		}
		return t;
	}
	return hook.apply(error, dataSignal);
}
 
Example 10
Source File: SchedulersTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
public void assertRejectingScheduler(Scheduler scheduler) {
	try {
		FluxIdentityProcessor<String> p = Processors.more().multicastNoBackpressure();

		AtomicReference<String> r = new AtomicReference<>();
		CountDownLatch l = new CountDownLatch(1);

		p.publishOn(scheduler)
		 .log()
		 .subscribe(r::set, null, l::countDown);

		scheduler.dispose();

		p.onNext("reject me");
		l.await(3, TimeUnit.SECONDS);
	}
	catch (Exception ree) {
		ree.printStackTrace();
		Throwable throwable = Exceptions.unwrap(ree);
		if (throwable instanceof RejectedExecutionException) {
			return;
		}
		fail(throwable + " is not a RejectedExecutionException");
	}
	finally {
		scheduler.dispose();
	}
}
 
Example 11
Source File: WingtipsSpringWebfluxComponentTest.java    From wingtips with Apache License 2.0 4 votes vote down vote up
@UseDataProvider("baseTracingStateWithSubspanOptionScenarioDataProvider")
@Test
public void verify_webflux_WebClient_call_with_error_in_Mono_of_ClientResponse_traced_correctly(
        BaseTracingStateScenario baseTracingStateScenario, boolean subspanOptionOn
) {
    // given
    TracingState baseTracingState = baseTracingStateScenario.setupBaseTracingState();
    Span parent = (baseTracingState == null) ? null : baseTracingState.spanStack.getFirst();

    String pathTemplateForTags = "/some/path/template/" + UUID.randomUUID().toString();

    WebClient webClientWithWingtips = WebClient
        .builder()
        .filter(
            new WingtipsSpringWebfluxExchangeFilterFunction(
                subspanOptionOn,
                SpringWebfluxClientRequestZipkinTagStrategy.getDefaultInstance(),
                new SpringHttpClientTagAdapterWithHttpRouteKnowledge(pathTemplateForTags)
            )
        )
        .build();

    // The call will never make it to the server, so we only expect one or zero spans completed,
    //      depending on the value of subspanOptionOn.
    int expectedNumSpansCompleted = (subspanOptionOn) ? 1 : 0;

    String fullRequestUrl = "http://localhost:1234567890" + BASIC_ENDPOINT_PATH + "?foo=bar";

    // when
    Throwable ex = catchThrowable(
        () -> webClientWithWingtips
            .get()
            .uri(fullRequestUrl)
            .attributes(baseTracingStateScenario.tracingStateAttrSetup(baseTracingState))
            .exchange()
            .block()
    );

    // then
    Throwable unwrappedEx = Exceptions.unwrap(ex);
    assertThat(unwrappedEx).isInstanceOf(UnknownHostException.class);
    waitUntilSpanRecorderHasExpectedNumSpans(expectedNumSpansCompleted);
    assertThat(spanRecorder.completedSpans).hasSize(expectedNumSpansCompleted);
    if (expectedNumSpansCompleted > 0) {
        Span errorSpan = spanRecorder.completedSpans.get(0);

        if (parent == null) {
            assertThat(errorSpan.getParentSpanId()).isNull();
        }
        else {
            assertThat(errorSpan.getTraceId()).isEqualTo(parent.getTraceId());
            assertThat(errorSpan.getParentSpanId()).isEqualTo(parent.getSpanId());
        }

        verifySpanNameAndTags(
            errorSpan,
            "GET " + pathTemplateForTags,
            null,
            "GET",
            BASIC_ENDPOINT_PATH,
            fullRequestUrl,
            pathTemplateForTags,
            null,
            unwrappedEx.getMessage(),
            "spring.webflux.client"
        );
        assertThat(errorSpan.getTags().get("webflux_log_id")).isNotEmpty();
    }

    if (parent != null) {
        parent.close();
    }
}
 
Example 12
Source File: WingtipsSpringWebfluxComponentTest.java    From wingtips with Apache License 2.0 4 votes vote down vote up
@UseDataProvider("baseTracingStateWithSubspanOptionScenarioDataProvider")
@Test
public void verify_webflux_WebClient_call_with_error_thrown_in_sub_filter_traced_correctly(
    BaseTracingStateScenario baseTracingStateScenario, boolean subspanOptionOn
) {
    // given
    TracingState baseTracingState = baseTracingStateScenario.setupBaseTracingState();
    Span parent = (baseTracingState == null) ? null : baseTracingState.spanStack.getFirst();

    String pathTemplateForTags = "/some/path/template/" + UUID.randomUUID().toString();

    RuntimeException subFilterEx = new RuntimeException(
        "Intentional test exception in secondary WebClient filter."
    );
    WebClient webClientWithWingtips = WebClient
        .builder()
        .filter(
            new WingtipsSpringWebfluxExchangeFilterFunction(
                subspanOptionOn,
                SpringWebfluxClientRequestZipkinTagStrategy.getDefaultInstance(),
                new SpringHttpClientTagAdapterWithHttpRouteKnowledge(pathTemplateForTags)
            )
        )
        .filter((request, next) -> {
            throw subFilterEx;
        })
        .build();

    // The call will never make it to the server, so we only expect one or zero spans completed,
    //      depending on the value of subspanOptionOn.
    int expectedNumSpansCompleted = (subspanOptionOn) ? 1 : 0;

    String fullRequestUrl = "http://localhost:1234567890" + BASIC_ENDPOINT_PATH + "?foo=bar";

    // when
    Throwable ex = catchThrowable(
        () -> webClientWithWingtips
            .get()
            .uri(fullRequestUrl)
            .attributes(baseTracingStateScenario.tracingStateAttrSetup(baseTracingState))
            .exchange()
            .block()
    );

    // then
    Throwable unwrappedEx = Exceptions.unwrap(ex);
    assertThat(unwrappedEx).isSameAs(subFilterEx);
    waitUntilSpanRecorderHasExpectedNumSpans(expectedNumSpansCompleted);
    assertThat(spanRecorder.completedSpans).hasSize(expectedNumSpansCompleted);
    if (expectedNumSpansCompleted > 0) {
        Span errorSpan = spanRecorder.completedSpans.get(0);

        if (parent == null) {
            assertThat(errorSpan.getParentSpanId()).isNull();
        }
        else {
            assertThat(errorSpan.getTraceId()).isEqualTo(parent.getTraceId());
            assertThat(errorSpan.getParentSpanId()).isEqualTo(parent.getSpanId());
        }

        verifySpanNameAndTags(
            errorSpan,
            "GET " + pathTemplateForTags,
            null,
            "GET",
            BASIC_ENDPOINT_PATH,
            fullRequestUrl,
            pathTemplateForTags,
            null,
            unwrappedEx.getMessage(),
            "spring.webflux.client"
        );
        assertThat(errorSpan.getTags().get("webflux_log_id")).isNotEmpty();
    }

    if (parent != null) {
        parent.close();
    }
}
 
Example 13
Source File: Operators.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
private static Throwable unwrapOnNextError(Throwable error) {
	return Exceptions.isBubbling(error) ? error : Exceptions.unwrap(error);
}