com.netflix.hystrix.exception.HystrixRuntimeException Java Examples

The following examples show how to use com.netflix.hystrix.exception.HystrixRuntimeException. 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: SetterFactoryTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void customSetter() {
  thrown.expect(HystrixRuntimeException.class);
  thrown.expectMessage("POST / failed and no fallback available.");

  server.enqueue(new MockResponse().setResponseCode(500));

  SetterFactory commandKeyIsRequestLine = (target, method) -> {
    String groupKey = target.name();
    String commandKey = method.getAnnotation(RequestLine.class).value();
    return HystrixCommand.Setter
        .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
        .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey));
  };

  TestInterface api = HystrixFeign.builder()
      .setterFactory(commandKeyIsRequestLine)
      .target(TestInterface.class, "http://localhost:" + server.getPort());

  api.invoke();
}
 
Example #2
Source File: HystrixFilterAsyncTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testHystrixTimeout() {
    providerConfig = defaultServer(2000);
    providerConfig.export();

    consumerConfig = defaultClient()
        .setTimeout(10000);

    HystrixService HystrixService = consumerConfig.refer();

    long start = System.currentTimeMillis();
    try {
        HystrixService.sayHello("abc", 24);
        Future future = SofaResponseFuture.getFuture();
        Assert.assertFalse(future.isDone());
        Assert.assertFalse(future.isCancelled());
        SofaResponseFuture.getResponse(10000, true);
        Assert.fail();
    } catch (Exception e) {
        Assert.assertTrue(e instanceof SofaRpcException);
        final Throwable cause = e.getCause();
        Assert.assertTrue(cause.getMessage(), cause instanceof HystrixRuntimeException);
        Assert.assertTrue((System.currentTimeMillis() - start) > HYSTRIX_DEFAULT_TIMEOUT);
    }
}
 
Example #3
Source File: HystrixFilterSyncTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testHystrixTimeout() {
    providerConfig = defaultServer(2000);
    providerConfig.export();

    consumerConfig = defaultClient()
        .setTimeout(10000);

    HystrixService helloService = consumerConfig.refer();

    try {
        helloService.sayHello("abc", 24);
        Assert.fail();
    } catch (Exception e) {
        Assert.assertTrue(e instanceof SofaRpcException);
        Assert.assertTrue(e.getCause() instanceof HystrixRuntimeException);
    }
}
 
Example #4
Source File: StoreApiTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteOrder() {
    Order order = createOrder();
    client.deleteOrder(order.getId().toString());
    client.placeOrder(order).execute();

    Order fetched = client.getOrderById(order.getId()).execute().getBody();
    assertEquals(fetched.getId(), order.getId());

    client.deleteOrder(String.valueOf(order.getId())).execute();

    try {
        client.getOrderById(order.getId()).execute();
        fail("expected an error");
    } catch (HystrixRuntimeException e) {
        assertTrue(e.getCause().getMessage().startsWith("status 404 "));
    }
}
 
Example #5
Source File: ExtResponseEntityDecoder.java    From onetwo with Apache License 2.0 6 votes vote down vote up
protected Object handleDataResult(FeignResponseAdapter response, Object res) {
	Object result = res;
	if (result instanceof DataResult) {
		DataResult<?> dr = (DataResult<?>) result;
		if(isCutoutError(response, dr)){
			ServiceException cause = new ServiceException(dr.getMessage(), dr.getCode());
			String message = "cutoutError, remote service error:"+dr.getMessage();
			JFishLoggerFactory.findMailLogger().error(message);
			
			throw new HystrixRuntimeException(FailureType.SHORTCIRCUIT, OkHttpRibbonCommand.class, message, cause, null);
		}else if(!dr.isSuccess()){
			throw new HystrixBadRequestException(dr.getMessage(), new ServiceException(dr.getMessage(), dr.getCode()));
		}
		res = dr.getData();
	}
	return result;
}
 
Example #6
Source File: TDPExceptionUtils.java    From data-prep with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to extract the TDPException out of the HystrixRuntimeException. If no TDPException is found, the
 * HystrixRuntimeException is wrapped into a TDPException.
 *
 * @param hre the HystrixRuntimeException to process.
 * @return the TDPException to throw.
 */
static TDPException processHystrixException(HystrixRuntimeException hre) {
    // filter out hystrix exception level if possible
    Throwable e = hre;
    TDPException innerMostTDPException = null;
    while (e.getCause() != null) {
        e = e.getCause();
        if (e instanceof TDPException) {
            innerMostTDPException = (TDPException) e;
        }
    }
    if (innerMostTDPException != null) {
        return innerMostTDPException;
    } else {
        return new TDPException(CommonErrorCodes.UNEXPECTED_SERVICE_EXCEPTION, hre);
    }
}
 
Example #7
Source File: HystrixReactiveHttpClientTest.java    From feign-reactive with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFailAsNoFallback() {

    expectedException.expect(HystrixRuntimeException.class);
    expectedException.expectMessage(containsString("failed and no fallback available"));

    String body = "success!";
    LoadBalancingReactiveHttpClientTest.mockSuccessAfterSeveralAttempts(server, "/", 1, 598,
            aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "application/json")
                    .withBody(body));

    LoadBalancingReactiveHttpClientTest.TestInterface client = CloudReactiveFeign.<LoadBalancingReactiveHttpClientTest.TestInterface>builder()
            .setHystrixCommandSetterFactory(getSetterFactory(testNo))
            .target(LoadBalancingReactiveHttpClientTest.TestInterface.class, "http://localhost:" + server.port());

    client.get().block();
}
 
Example #8
Source File: TDPExceptionUtilsTest.java    From data-prep with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFallbackTDPException() {
    // given
    final HystrixRuntimeException hre = new HystrixRuntimeException( //
            BAD_REQUEST_EXCEPTION, //
            TestHystrixCommand.class, //
            "hello", //
            new Exception("middle", new IllegalArgumentException("root")), //
            new Throwable("fallback")//
    );

    // when
    final TDPException tdpException = TDPExceptionUtils.processHystrixException(hre);

    // then
    assertNotNull(tdpException);
    assertEquals(UNEXPECTED_SERVICE_EXCEPTION, tdpException.getCode());
}
 
Example #9
Source File: TenacityExceptionMapper.java    From tenacity with Apache License 2.0 6 votes vote down vote up
public static boolean isTenacityException(HystrixRuntimeException exception) {
    switch (exception.getFailureType()) {
        case TIMEOUT:
        case SHORTCIRCUIT:
        case REJECTED_THREAD_EXECUTION:
        case REJECTED_SEMAPHORE_EXECUTION:
        case REJECTED_SEMAPHORE_FALLBACK:
            return true;
        case COMMAND_EXCEPTION:
            //TODO: Remove this and set to false by default
            //SocketTimeoutExceptions should be fixed by the application if they are being thrown within the context
            //of a TenacityCommand
            return exception.getCause() instanceof SocketTimeoutException;
        default:
            return false;
    }
}
 
Example #10
Source File: ExceptionLoggingCommandHookIntegrationTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotLogWhenShortCircuited() {
    final DefaultExceptionLogger defaultExceptionLogger = spy(new DefaultExceptionLogger());
    HystrixPlugins.getInstance().registerCommandExecutionHook(new ExceptionLoggingCommandHook(defaultExceptionLogger));

    try {
        new AlwaysShortCircuit().execute();
    } catch (HystrixRuntimeException err) {
        assertThat(Throwables.getCausalChain(err)
                .stream()
                .filter(AuthenticationException.class::isInstance)
                .findAny())
                .isNotEmpty();
    }

    verifyZeroInteractions(defaultExceptionLogger);
}
 
Example #11
Source File: TenacityAuthenticatorTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLogWhenExceptionIsThrown() throws AuthenticationException {
    final DefaultExceptionLogger defaultExceptionLogger = spy(new DefaultExceptionLogger());
    HystrixPlugins.getInstance().registerCommandExecutionHook(new ExceptionLoggingCommandHook(defaultExceptionLogger));
    when(mockAuthenticator.authenticate(any(BasicCredentials.class))).thenThrow(new AuthenticationException("test"));
    doCallRealMethod().when(defaultExceptionLogger).log(any(Exception.class), any(HystrixCommand.class));

    try {
        tenacityAuthenticator.authenticate(new BasicCredentials("foo", "foo"));
    } catch (HystrixRuntimeException err) {
        assertThat(Throwables.getCausalChain(err)
                .stream()
                .filter(AuthenticationException.class::isInstance)
                .findAny())
        .isNotEmpty();
    }

    verify(mockAuthenticator, times(1)).authenticate(any(BasicCredentials.class));
    verify(defaultExceptionLogger, times(1)).log(any(Exception.class), any(HystrixCommand.class));
}
 
Example #12
Source File: TenacityAuthenticatorTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotTransformAuthenticationExceptionIntoMappedException() throws AuthenticationException {
    when(AuthenticatorApp.getMockAuthenticator().authenticate(any(BasicCredentials.class))).thenThrow(new AuthenticationException("test"));
    final Client client = new JerseyClientBuilder(new MetricRegistry())
            .using(executorService, Jackson.newObjectMapper())
            .build("dropwizard-app-rule");

    client.register(HttpAuthenticationFeature.basicBuilder()
            .nonPreemptive()
            .credentials("user", "stuff")
            .build());

    final Response response = client
            .target(URI.create("http://localhost:" + RULE.getLocalPort() + "/auth"))
            .request()
            .get(Response.class);

    assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());

    verify(AuthenticatorApp.getMockAuthenticator(), times(1)).authenticate(any(BasicCredentials.class));
    verifyZeroInteractions(AuthenticatorApp.getTenacityContainerExceptionMapper());
    verify(AuthenticatorApp.getTenacityExceptionMapper(), times(1)).toResponse(any(HystrixRuntimeException.class));
}
 
Example #13
Source File: TenacityExceptionMapperTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldStillThrowServerError() {
    setupFailureType(HystrixRuntimeException.FailureType.COMMAND_EXCEPTION);

    try {
        resources.client()
                .target("/random")
                .request()
                .get(String.class);
    } catch (InternalServerErrorException err) {
        assertThat(err.getResponse().getStatus())
                .isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    }

    verify(mockFactory, times(1)).from(anyString());
}
 
Example #14
Source File: ClientTimeoutTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void tenacityDoesntRaceWithJerseyTimeout() {
    clientConfiguration.setTimeout(Duration.milliseconds(1));
    tenacityConfiguration.setExecutionIsolationThreadTimeoutInMillis(300);
    registerTenacityProperties();

    final Client client = tenacityClientBuilder.build(buildClient());
    final WebTarget spyTarget = spy(client.target(uri));
    final VoidCommand command = new VoidCommand(spyTarget, Duration.milliseconds(500));

    boolean timeoutFailure = false;
    try {
        command.execute();
    } catch (HystrixRuntimeException err) {
        timeoutFailure = err.getFailureType().equals(HystrixRuntimeException.FailureType.TIMEOUT);
    }

    assertTrue(timeoutFailure);
    assertTrue(command.isResponseTimedOut());
}
 
Example #15
Source File: HystrixBuilderTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void errorInFallbackHasExpectedBehavior() {
  thrown.expect(HystrixRuntimeException.class);
  thrown.expectMessage("GitHub#contributors(String,String) failed and fallback failed.");
  thrown.expectCause(
      isA(FeignException.class)); // as opposed to RuntimeException (from the fallback)

  server.enqueue(new MockResponse().setResponseCode(500));

  final GitHub fallback = (owner, repo) -> {
    throw new RuntimeException("oops");
  };

  final GitHub api = target(GitHub.class, "http://localhost:" + server.getPort(), fallback);

  api.contributors("Netflix", "feign");
}
 
Example #16
Source File: HystrixBuilderTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void rxObservableListFall_noFallback() {
  server.enqueue(new MockResponse().setResponseCode(500));

  final TestInterface api = targetWithoutFallback();

  final Observable<List<String>> observable = api.listObservable();

  assertThat(observable).isNotNull();
  assertThat(server.getRequestCount()).isEqualTo(0);

  final TestSubscriber<List<String>> testSubscriber = new TestSubscriber<List<String>>();
  observable.subscribe(testSubscriber);
  testSubscriber.awaitTerminalEvent();

  assertThat(testSubscriber.getOnNextEvents()).isEmpty();
  assertThat(testSubscriber.getOnErrorEvents().get(0))
      .isInstanceOf(HystrixRuntimeException.class)
      .hasMessage("TestInterface#listObservable() failed and no fallback available.");
}
 
Example #17
Source File: TenacityAuthenticatorTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test(expected = HystrixRuntimeException.class)
public void shouldThrowWhenAuthenticateTimesOut() throws AuthenticationException {
    final TenacityConfiguration overrideConfiguration = new TenacityConfiguration();
    overrideConfiguration.setExecutionIsolationThreadTimeoutInMillis(1);

    new TenacityPropertyRegister(
            ImmutableMap.of(DependencyKey.TENACITY_AUTH_TIMEOUT, overrideConfiguration),
            new BreakerboxConfiguration(),
            mock(ArchaiusPropertyRegister.class))
            .register();

    when(mockAuthenticator.authenticate(any(BasicCredentials.class))).thenAnswer((invocation) -> {
        Thread.sleep(50);
        return new Object();
    });

    try {
        assertThat(tenacityAuthenticator.authenticate(new BasicCredentials("credentials", "credentials")))
                .isEqualTo(Optional.empty());
    } catch (HystrixRuntimeException err) {
        assertThat(err.getFailureType()).isEqualTo(HystrixRuntimeException.FailureType.TIMEOUT);
        throw err;
    }
}
 
Example #18
Source File: HystrixBuilderTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void completableFutureFailWithoutFallback() throws TimeoutException, InterruptedException {
  server.enqueue(new MockResponse().setResponseCode(500));

  final TestInterface api = target(TestInterface.class, "http://localhost:" + server.getPort());

  final CompletableFuture<String> completable = api.completableFuture();

  assertThat(completable).isNotNull();

  try {
    completable.get(5, TimeUnit.SECONDS);
  } catch (final ExecutionException e) {
    assertThat(e).hasCauseInstanceOf(HystrixRuntimeException.class);
  }
}
 
Example #19
Source File: HystrixBuilderTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void rxCompletableFailWithoutFallback() {
  server.enqueue(new MockResponse().setResponseCode(500));

  final TestInterface api = target(TestInterface.class, "http://localhost:" + server.getPort());

  final Completable completable = api.completable();

  assertThat(completable).isNotNull();
  assertThat(server.getRequestCount()).isEqualTo(0);

  final TestSubscriber<String> testSubscriber = new TestSubscriber<String>();
  completable.subscribe(testSubscriber);
  testSubscriber.awaitTerminalEvent();

  testSubscriber.assertError(HystrixRuntimeException.class);
}
 
Example #20
Source File: TDPExceptionUtilsTest.java    From data-prep with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldExtractTDPException() {
    // given
    TDPException expected = new TDPException(UNABLE_TO_CONNECT_TO_STREAMS);
    final HystrixRuntimeException hre = new HystrixRuntimeException( //
            BAD_REQUEST_EXCEPTION, //
            TestHystrixCommand.class, //
            "hello", //
            new Exception("middle", expected), //
            new Throwable("fallback")//
    );

    // when
    final TDPException tdpException = TDPExceptionUtils.processHystrixException(hre);

    // then
    assertNotNull(tdpException);
    assertEquals(UNABLE_TO_CONNECT_TO_STREAMS, tdpException.getCode());
}
 
Example #21
Source File: AnalyticsServiceTest.java    From twitch4j with MIT License 5 votes vote down vote up
/**
 * Get Game Analytics
 */
@Test
@DisplayName("Fetch game analytics")
@Disabled
public void getGameAnalytics() {
    // TestCase
    try {
        GameAnalyticsList resultList = testUtils.getTwitchHelixClient().getGameAnalyticUrl(testUtils.getCredential().getAccessToken(), null, 10, null, null, null, null).execute();
    } catch (HystrixRuntimeException ex) {
        String responseBody = (String) ((ContextedRuntimeException) ex.getCause()).getFirstContextValue("responseBody");
        System.out.println(responseBody);
        //assertTrue(responseBody.contains("User Does Not Have Extensions"), "Test Account does not have extensions!");
    }
}
 
Example #22
Source File: HystrixTimeoutManualTest.java    From tutorials with MIT License 5 votes vote down vote up
public String invokeRemoteService(HystrixCommand.Setter config, int timeout)
  throws InterruptedException {
    String response = null;
    try {
        response = new RemoteServiceTestCommand(config,
          new RemoteServiceTestSimulator(timeout)).execute();
    } catch (HystrixRuntimeException ex) {
        System.out.println("ex = " + ex);
    }
    return response;
}
 
Example #23
Source File: TenacityExceptionMapper.java    From tenacity with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(HystrixRuntimeException exception) {
    if (isTenacityException(exception)) {
        LOGGER.debug("Unhandled HystrixRuntimeException", exception);
        return Response.status(statusCode).build(); //TODO: Retry-After for 429
    }

    LOGGER.warn("HystrixRuntimeException is not mappable to a status code: {}", exception);

    return Response.serverError().build();
}
 
Example #24
Source File: HystrixTimeoutManualTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = HystrixRuntimeException.class)
public void givenSvcTimeoutOf10000AndDefaultSettings__whenRemoteSvcExecuted_thenExpectHRE() throws InterruptedException {
    HystrixCommand.Setter config = HystrixCommand
      .Setter
      .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest3"));
    new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute();
}
 
Example #25
Source File: RegisterClientHelper.java    From Java-Auto-Update with Apache License 2.0 5 votes vote down vote up
public ClientConfig registerClient() {
    BackOff exponentialBackOff = new ExponentialBackOff();
    BackOffExecution backOffExecution = exponentialBackOff.start();

    while (true) {
        try {
            return new CommandRegisterClient(artifactId, configServiceClient, clientName, clientId).execute();
        } catch (HystrixRuntimeException e) {
            RegisterClientExceptionHandler.handleRegisterClientException(e, exponentialBackOff, backOffExecution,
                    configServiceClient.getUrl());
        }
    }
}
 
Example #26
Source File: HystrixTimeoutManualTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = HystrixRuntimeException.class)
public void givenSvcTimeoutOf15000AndExecTimeoutOf5000__whenExecuted_thenExpectHRE()
  throws InterruptedException {
    HystrixCommand.Setter config = HystrixCommand
      .Setter
      .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest5"));
    HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
    commandProperties.withExecutionTimeoutInMilliseconds(5_000);
    config.andCommandPropertiesDefaults(commandProperties);
    new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(15_000)).execute();
}
 
Example #27
Source File: TenacityCommandBuilderTest.java    From tenacity with Apache License 2.0 5 votes vote down vote up
@Test(expected = HystrixRuntimeException.class)
public void commandThatAlwaysShouldCallFallbackAndItDoesntExist() {
    TenacityCommand
            .builder(DependencyKey.GENERAL)
            .run(() -> {throw new RuntimeException();})
            .execute();
}
 
Example #28
Source File: TenacityObservableCommandTest.java    From tenacity with Apache License 2.0 5 votes vote down vote up
private static void executeTimeoutAndVerify(final TenacityObservableCommand<Boolean> timeoutCommand) throws InterruptedException {
    timeoutCommand.getCumulativeCommandEventCounterStream().startCachingStreamValuesIfUnstarted();
    try {
        assertTrue(timeoutCommand.observe().toBlocking().single());
    } catch (HystrixRuntimeException err) {
        assertEquals(err.getFailureType(), HystrixRuntimeException.FailureType.TIMEOUT);
    }

    Thread.sleep(1000);

    assertEquals(timeoutCommand.isResponseTimedOut(), true);
    assertEquals(timeoutCommand.getMetrics().getCumulativeCount(HystrixRollingNumberEvent.TIMEOUT), 1);
}
 
Example #29
Source File: CommandThatFailsFast.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailure() {
    try {
        new CommandThatFailsFast(true).execute();
        fail("we should have thrown an exception");
    } catch (HystrixRuntimeException e) {
        assertEquals("failure from CommandThatFailsFast", e.getCause().getMessage());
        e.printStackTrace();
    }
}
 
Example #30
Source File: ConnoteCommand.java    From resilient-transport-service with Apache License 2.0 5 votes vote down vote up
@Override
protected ConnoteDTO getFallback() {

    if (secondTry) {
        LOGGER.debug(LOGGER.isDebugEnabled() ? "Second Connote Service Call started" : null);

        ConnoteCommand connoteCommand = new ConnoteCommand(restTemplate, false);
        return connoteCommand.execute();

    } else {

        LOGGER.debug(LOGGER.isDebugEnabled() ? "Fallback Connote Service call" : null);

        ConnoteDTO connoteDTO = new ConnoteDTO();
        connoteDTO.setFallback(true);

        if (getExecutionException() != null) {
            Exception exceptionFromThrowable = getExceptionFromThrowable(getExecutionException());

            if (exceptionFromThrowable == null) {
                connoteDTO.setErrorMsg("Unable to check exception type");

            } else if (exceptionFromThrowable instanceof HystrixRuntimeException) {
                HystrixRuntimeException hystrixRuntimeException = (HystrixRuntimeException) exceptionFromThrowable;
                connoteDTO.setErrorMsg(hystrixRuntimeException.getFailureType().name());

            } else if (exceptionFromThrowable instanceof HystrixTimeoutException) {
                connoteDTO.setErrorMsg(HystrixRuntimeException.FailureType.TIMEOUT.name());
            } else {

                connoteDTO.setErrorMsg(exceptionFromThrowable.getMessage());
            }

        } else
            connoteDTO.setErrorMsg("unable to create connote");
        return connoteDTO;
    }
}