类org.springframework.core.NestedExceptionUtils源码实例Demo

下面列出了怎么用org.springframework.core.NestedExceptionUtils的API类实例代码及写法,或者点击链接到github查看源代码。

@Ignore("Fix me, I'm flaky!")
@Test
public void testWebClientCustomTracing() {
    try {
        webClient.get()
                .uri(URI.create("http://nonexisting.example.com"))
                .retrieve()
                .bodyToMono(String.class)
                .block();
    } catch (final RuntimeException e) {
        Assert.assertTrue(NestedExceptionUtils.getRootCause(e) instanceof UnknownHostException);
    }

    Assert.assertEquals(1, mockTracer.finishedSpans().size());
    Assert.assertEquals("foo", mockTracer.finishedSpans().get(0).tags().get("custom-test"));
}
 
private void assertExceptions(List<ProjectUrlAndException> projectUrlAndExceptions) {
	String exceptionMessages = projectUrlAndExceptions.stream()
			.filter(ProjectUrlAndException::hasException)
			.map(e -> "Project [" + e.key + "] for url [" + e.url + "] "
					+ "has exception [\n\n"
					+ Arrays.stream(NestedExceptionUtils.getMostSpecificCause(e.ex)
							.getStackTrace()).map(StackTraceElement::toString)
							.collect(Collectors.joining("\n"))
					+ "]")
			.collect(Collectors.joining("\n"));
	if (StringUtils.hasText(exceptionMessages)) {
		throw new IllegalStateException(
				"Exceptions were found while running post release tasks\n"
						+ exceptionMessages);
	}
	else {
		log.info("No exceptions were found while running post release tasks");
	}
}
 
@Test
public void testNestedServletExceptionStringThrowable() {
	Throwable cause = new RuntimeException();
	NestedServletException exception = new NestedServletException("foo", cause);
	assertEquals(NestedExceptionUtils.buildMessage("foo", cause), exception.getMessage());
	assertEquals(cause, exception.getCause());
}
 
private boolean isDisconnectedClientError(Throwable ex) {
	String message = NestedExceptionUtils.getMostSpecificCause(ex).getMessage();
	if (message != null) {
		String text = message.toLowerCase();
		if (text.contains("broken pipe") || text.contains("connection reset by peer")) {
			return true;
		}
	}
	return DISCONNECTED_CLIENT_EXCEPTIONS.contains(ex.getClass().getSimpleName());
}
 
@Test
public void testNestedServletExceptionStringThrowable() {
	Throwable cause = new RuntimeException();
	NestedServletException exception = new NestedServletException("foo", cause);
	assertEquals(NestedExceptionUtils.buildMessage("foo", cause), exception.getMessage());
	assertEquals(cause, exception.getCause());
}
 
源代码6 项目: cucumber-rest-steps   文件: RestSteps.java
private <T> T withAssertion(Supplier<T> supplier) {
  try {
    return supplier.get();
  } catch (AssertionError error) {
    initExpectBody();
    final EntityExchangeResult<byte[]> entityExchangeResult = expectBody.returnResult();
    throw new AssertionError(NestedExceptionUtils.getMostSpecificCause(error).getMessage() + "\n" + entityExchangeResult);
  }
}
 
源代码7 项目: cucumber-rest-steps   文件: RestSteps.java
private void withAssertion(Consumer<Void> consumer) {
  try {
    consumer.accept(null);
  } catch (AssertionError error) {
    initExpectBody();
    final EntityExchangeResult<byte[]> entityExchangeResult = expectBody.returnResult();
    throw new AssertionError(NestedExceptionUtils.getMostSpecificCause(error).getMessage() + "\n" + entityExchangeResult);
  }
}
 
@Test
public void testErrorUnknownHostException() {
    String url = "http://nonexisting.example.com";
    try {
        client.getForEntity(url, String.class);
    } catch (RuntimeException ex) {
        Assert.assertTrue(NestedExceptionUtils.getRootCause(ex) instanceof UnknownHostException);
        //ok UnknownHostException
    }

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(1, mockSpans.size());

    MockSpan mockSpan = mockSpans.get(0);
    Assert.assertEquals("GET", mockSpan.operationName());
    Assert.assertEquals(5, mockSpan.tags().size());
    Assert.assertEquals(componentName, mockSpan.tags().get(Tags.COMPONENT.getKey()));
    Assert.assertEquals(Tags.SPAN_KIND_CLIENT, mockSpan.tags().get(Tags.SPAN_KIND.getKey()));
    Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey()));
    Assert.assertEquals(url, mockSpan.tags().get(Tags.HTTP_URL.getKey()));
    Assert.assertEquals(Boolean.TRUE, mockSpan.tags().get(Tags.ERROR.getKey()));

    Assert.assertEquals(1, mockSpan.logEntries().size());
    Assert.assertEquals(2, mockSpan.logEntries().get(0).fields().size());
    Assert.assertEquals(Tags.ERROR.getKey(), mockSpan.logEntries().get(0).fields().get("event"));
    Assert.assertNotNull(mockSpan.logEntries().get(0).fields().get("error.object"));
}
 
Table(String creationTime, String executionTime, String projectName,
		String taskCaption, String taskDescription, String taskState,
		List<Throwable> exceptions) {
	this.creationTime = creationTime;
	this.executionTime = executionTime;
	this.projectName = projectName;
	this.taskCaption = taskCaption;
	this.taskDescription = taskDescription;
	this.taskState = taskState;
	this.thrownException = exceptions == null ? "" : exceptions.stream()
			// TODO: Last but most specific
			.map(t -> NestedExceptionUtils.getMostSpecificCause(t).toString())
			.collect(Collectors.joining("\n"));
	this.exceptions = exceptions;
}
 
@Test
public void testNestedServletExceptionStringThrowable() {
	Throwable cause = new RuntimeException();
	NestedServletException exception = new NestedServletException("foo", cause);
	assertEquals(NestedExceptionUtils.buildMessage("foo", cause), exception.getMessage());
	assertEquals(cause, exception.getCause());
}
 
@Test
public void contextFailsToLoad() {
	try {
		SpringApplication.run(TestConfiguration.class,
				"--spring.cloud.compatibility-verifier.compatible-boot-versions=1.2.x,1.3.x");
		BDDAssertions.fail("should throw exception");
	}
	catch (BeanCreationException ex) {
		Throwable cause = NestedExceptionUtils.getRootCause(ex);
		then(((CompatibilityNotMetException) cause).results).hasSize(1);
	}
}
 
@Override
public Environment findOne(String config, String profile, String label,
		boolean includeOrigin) {
	SpringApplicationBuilder builder = new SpringApplicationBuilder(
			PropertyPlaceholderAutoConfiguration.class);
	ConfigurableEnvironment environment = getEnvironment(profile);
	builder.environment(environment);
	builder.web(WebApplicationType.NONE).bannerMode(Mode.OFF);
	if (!logger.isDebugEnabled()) {
		// Make the mini-application startup less verbose
		builder.logStartupInfo(false);
	}
	String[] args = getArgs(config, profile, label);
	// Explicitly set the listeners (to exclude logging listener which would change
	// log levels in the caller)
	builder.application()
			.setListeners(Arrays.asList(new ConfigFileApplicationListener()));

	try (ConfigurableApplicationContext context = builder.run(args)) {
		environment.getPropertySources().remove("profiles");
		return clean(new PassthruEnvironmentRepository(environment).findOne(config,
				profile, label, includeOrigin));
	}
	catch (Exception e) {
		String msg = String.format(
				"Could not construct context for config=%s profile=%s label=%s includeOrigin=%b",
				config, profile, label, includeOrigin);
		String completeMessage = NestedExceptionUtils.buildMessage(msg,
				NestedExceptionUtils.getMostSpecificCause(e));
		throw new FailedToConstructEnvironmentException(completeMessage, e);
	}
}
 
private boolean indicatesDisconnectedClient(Throwable ex)  {
	String message = NestedExceptionUtils.getMostSpecificCause(ex).getMessage();
	message = (message != null ? message.toLowerCase() : "");
	String className = ex.getClass().getSimpleName();
	return (message.contains("broken pipe") || DISCONNECTED_CLIENT_EXCEPTIONS.contains(className));
}
 
@Override
public String getMessage() {
	String msg = this.status + (this.reason != null ? " \"" + this.reason + "\"" : "");
	return NestedExceptionUtils.buildMessage(msg, getCause());
}
 
/**
 * Return the detail message, including the message from the nested exception
 * if there is one.
 */
@Override
@Nullable
public String getMessage() {
	return NestedExceptionUtils.buildMessage(super.getMessage(), getCause());
}
 
private boolean indicatesDisconnectedClient(Throwable ex)  {
	String message = NestedExceptionUtils.getMostSpecificCause(ex).getMessage();
	message = (message != null ? message.toLowerCase() : "");
	String className = ex.getClass().getSimpleName();
	return (message.contains("broken pipe") || DISCONNECTED_CLIENT_EXCEPTIONS.contains(className));
}
 
@Override
public String getMessage() {
	String msg = this.status + (this.reason != null ? " \"" + this.reason + "\"" : "");
	return NestedExceptionUtils.buildMessage(msg, getCause());
}
 
private boolean isDisconnectedClientError(Throwable ex)  {
	String message = NestedExceptionUtils.getMostSpecificCause(ex).getMessage();
	message = (message != null ? message.toLowerCase() : "");
	String className = ex.getClass().getSimpleName();
	return (message.contains("broken pipe") || DISCONNECTED_CLIENT_EXCEPTIONS.contains(className));
}
 
/**
 * Return the detail message, including the message from the nested exception
 * if there is one.
 */
@Override
@Nullable
public String getMessage() {
	return NestedExceptionUtils.buildMessage(super.getMessage(), getCause());
}
 
源代码20 项目: lams   文件: NestedServletException.java
/**
 * Return the detail message, including the message from the nested exception
 * if there is one.
 */
@Override
public String getMessage() {
	return NestedExceptionUtils.buildMessage(super.getMessage(), getCause());
}
 
/**
 * Return the detail message, including the message from the nested exception
 * if there is one.
 */
@Override
public String getMessage() {
	return NestedExceptionUtils.buildMessage(super.getMessage(), getCause());
}
 
/**
 * Copied from Spring Boot 2's {@code AbstractErrorWebExceptionHandler} class.
 */
public static boolean isDisconnectedClientError(Throwable ex) {
    return DISCONNECTED_CLIENT_EXCEPTIONS.contains(ex.getClass().getSimpleName())
           || isDisconnectedClientErrorMessage(NestedExceptionUtils.getMostSpecificCause(ex).getMessage());
}
 
private void handleErrNoSuchKeyError(NonTransientDataAccessException ex) {
	if (!"ERR no such key".equals(NestedExceptionUtils.getMostSpecificCause(ex).getMessage())) {
		throw ex;
	}
}
 
 类所在包
 类方法
 同包方法