/** * Propagate a {@link Throwable} as a {@link RuntimeException}. * <p> * Like Guava {@link Throwables#propagate(Throwable)} but: * <li> throws {@link RuntimeInterruptedException} to handle {@link InterruptedException}s; and * <li> wraps as PropagatedRuntimeException for easier filtering */ public static RuntimeException propagate(Throwable throwable) { if (throwable instanceof InterruptedException) { throw new RuntimeInterruptedException((InterruptedException) throwable); } else if (throwable instanceof RuntimeInterruptedException) { Thread.currentThread().interrupt(); throw (RuntimeInterruptedException) throwable; } Throwables.propagateIfPossible(checkNotNull(throwable)); throw new PropagatedRuntimeException(throwable); }
/** Callers should typically *not* attempt to summarise the cause in the message here; use toString() to get extended information */ public PropagatedRuntimeException(String message, Throwable cause) { super(message, cause); warnIfWrapping(cause); causeEmbeddedInMessage = checkCauseEmbedded(); }
private boolean checkCauseEmbedded() { String causalText = Exceptions.collapseText(getCause()); if (Strings.isBlank(causalText)) return false; return getMessage().endsWith(causalText); }
visited.add(t2); if (t2 instanceof PropagatedRuntimeException) { if (((PropagatedRuntimeException)t2).isCauseEmbeddedInMessage()) String causeResult = collapseTextInContext(new PropagatedRuntimeException(cause), contexts); if (result.indexOf(causeResult)>=0) return result;
@Override public String toString() { if (causeEmbeddedInMessage) { return super.toString(); } else { return Exceptions.appendSeparator(super.toString(), Exceptions.collapseText(getCause())); } }
return new PropagatedRuntimeException("Huge stack trace (size "+chain.size()+", removing all but last few), " + "starting: "+chain.get(0).getClass().getName()+": "+msg+"; ultimately caused by: ", chain.get(chain.size() - 10)); if (collapsed instanceof PropagatedRuntimeException && ((PropagatedRuntimeException)collapsed).isCauseEmbeddedInMessage()) { message = collapsedS; messageIsFinal = true; return new PropagatedRuntimeException(message, collapseCausalChain ? collapsed : source, Strings.isNonBlank(message));
private static RuntimeException propagate(String msg, Throwable throwable, boolean alwaysAnnotate) { if (throwable instanceof InterruptedException) { throw new RuntimeInterruptedException(msg, (InterruptedException) throwable); } else if (throwable instanceof RuntimeInterruptedException) { Thread.currentThread().interrupt(); if (alwaysAnnotate) { throw new RuntimeInterruptedException(msg, (RuntimeInterruptedException) throwable); } else { throw (RuntimeInterruptedException) throwable; } } if (throwable==null) { throw new PropagatedRuntimeException(msg, new NullPointerException("No throwable supplied.")); } if (!alwaysAnnotate) { Throwables.propagateIfPossible(checkNotNull(throwable)); } throw new PropagatedRuntimeException(msg, throwable); }
public PropagatedRuntimeException(String messagePart1, String messagePart2PossiblyIncludingPart1, Throwable cause) { super(messagePart2PossiblyIncludingPart1!=null && messagePart2PossiblyIncludingPart1.startsWith(messagePart1) ? messagePart2PossiblyIncludingPart1 : messagePart1+messagePart2PossiblyIncludingPart1, cause); warnIfWrapping(cause); causeEmbeddedInMessage = checkCauseEmbedded(); }
/** creates the given exception, but without propagating it, for use when caller will be wrapping */ public static RuntimeException create(@Nullable String prefix, Iterable<? extends Throwable> exceptions) { if (Iterables.size(exceptions)==1) { Throwable e = exceptions.iterator().next(); if (Strings.isBlank(prefix)) return new PropagatedRuntimeException(e); return new PropagatedRuntimeException(prefix + ": " + Exceptions.collapseText(e), e); } if (Iterables.isEmpty(exceptions)) { if (Strings.isBlank(prefix)) return new CompoundRuntimeException("(empty compound exception)", exceptions); return new CompoundRuntimeException(prefix, exceptions); } if (Strings.isBlank(prefix)) return new CompoundRuntimeException(Iterables.size(exceptions)+" errors, including: " + Exceptions.collapseText(exceptions.iterator().next()), exceptions); return new CompoundRuntimeException(prefix+"; "+Iterables.size(exceptions)+" errors including: " + Exceptions.collapseText(exceptions.iterator().next()), exceptions); }
@Test public void testNestedPropWithMessage() { Throwable t; t = new IOException("1"); t = new org.apache.brooklyn.util.exceptions.PropagatedRuntimeException(t); t = new org.apache.brooklyn.util.exceptions.PropagatedRuntimeException("A", t); Assert.assertEquals(Exceptions.collapseText(t), "A: IOException: 1"); }
@Test public void testBasicSoftwareProcessStopSomeModes() throws Exception { for (boolean isEntityStopped : new boolean[] {true, false}) { StopMode stopProcessMode = StopMode.IF_NOT_STOPPED; StopMode stopMachineMode = StopMode.IF_NOT_STOPPED; try { testBasicSoftwareProcessStopModes(stopProcessMode, stopMachineMode, isEntityStopped); } catch (Exception e) { String msg = "stopProcessMode: " + stopProcessMode + ", stopMachineMode: " + stopMachineMode + ", isEntityStopped: " + isEntityStopped; throw new PropagatedRuntimeException(msg, e); } } }
@Test public void testNestedExecAndProp() { Throwable t; t = new IOException("1"); t = new org.apache.brooklyn.util.exceptions.PropagatedRuntimeException(t); t = new java.util.concurrent.ExecutionException(t); Assert.assertEquals(Exceptions.collapseText(t), "IOException: 1"); }
public static Integer getMyPid() { try { java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean(); java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm"); jvm.setAccessible(true); // sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime); Object mgmt = jvm.get(runtime); java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId"); pid_method.setAccessible(true); return (Integer) pid_method.invoke(mgmt); } catch (Exception e) { throw new PropagatedRuntimeException("Test depends on (fragile) getMyPid method which does not work here", e); } }
@Test public void testComplexJcloudsExample() { Throwable t; t = new IOException("POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1 -> HTTP/1.1 401 Unauthorized"); t = new IllegalStateException("Not authorized to access cloud JcloudsLocation[aws-ec2:foo/aws-ec2@SEk63t8T]", t); t = new java.util.concurrent.ExecutionException(t); t = new org.apache.brooklyn.util.exceptions.PropagatedRuntimeException(t); t = new org.apache.brooklyn.util.exceptions.PropagatedRuntimeException("Error invoking start at EmptySoftwareProcessImpl{id=GVYo7Cth}", t); t = new java.util.concurrent.ExecutionException(t); t = new org.apache.brooklyn.util.exceptions.PropagatedRuntimeException(t); t = new java.util.concurrent.ExecutionException(t); t = new org.apache.brooklyn.util.exceptions.PropagatedRuntimeException(t); t = new java.util.concurrent.ExecutionException(t); t = new org.apache.brooklyn.util.exceptions.PropagatedRuntimeException(t); t = new org.apache.brooklyn.util.exceptions.PropagatedRuntimeException("Error invoking start at BasicApplicationImpl{id=fbihp1mo}", t); t = new java.util.concurrent.ExecutionException(t); String collapsed = Exceptions.collapseText(t); // should say IOException and POST Assert.assertTrue(collapsed.contains("IOException"), collapsed); Assert.assertTrue(collapsed.matches(".*POST.*"), collapsed); // should not contain propagated or POST twice Assert.assertFalse(collapsed.contains("Propagated"), collapsed); Assert.assertFalse(collapsed.matches(".*POST.*POST.*"), collapsed); }
@Test public void test12CollapsePropagatedExecutionCompoundBoring() throws Exception { RuntimeException e = new PropagatedRuntimeException("test1", new ExecutionException(Exceptions.create(MutableSet.of(new IllegalStateException("test2"), new IllegalStateException("test3"))))); assert12StandardChecks(e, true); }
private EntitySpec<?> resolve( Collection<EntitySpecResolver> resolvers, String localType, BrooklynClassLoadingContext loader, Set<String> encounteredTypes) { Collection<String> resolversWhoDontSupport = new ArrayList<String>(); Collection<Exception> otherProblemsFromResolvers = new ArrayList<Exception>(); for (EntitySpecResolver resolver : resolvers) { if (resolver.accepts(localType, loader)) { try { EntitySpec<?> spec = resolver.resolve(localType, loader, encounteredTypes); if (spec != null) { return spec; } else { resolversWhoDontSupport.add(resolver.getName() + " (returned null)"); } } catch (Exception e) { otherProblemsFromResolvers.add(new PropagatedRuntimeException("Transformer for "+resolver.getName()+" gave an error creating this plan: ", Exceptions.collapseText(e), e)); } } } if (!otherProblemsFromResolvers.isEmpty()) { // at least one thought he could do it log.debug("Type " + localType + " could not be resolved; failure will be propagated (other transformers tried = "+resolversWhoDontSupport+"): "+otherProblemsFromResolvers); throw otherProblemsFromResolvers.size()==1 ? Exceptions.create(null, otherProblemsFromResolvers) : Exceptions.create("ServiceSpecResolvers all failed", otherProblemsFromResolvers); } return null; }
/** @throws WebApplicationException with an ApiError as its body and the given status as its response code. * Exception and/or format can be null, and will be filled in / prefixed as appropriate. */ public static WebApplicationException throwWebApplicationException(Response.Status status, Throwable exception, String format, Object... args) { String suppliedMsg = format==null ? null : String.format(format, args); String fullMsg = suppliedMsg; if (exception!=null) { if (fullMsg==null) fullMsg = Exceptions.collapseText(exception); else fullMsg = suppliedMsg + ": "+Exceptions.collapseText(exception); } if (log.isDebugEnabled()) { log.debug("responding {} {} ({})", new Object[]{status.getStatusCode(), status.getReasonPhrase(), fullMsg}); } ApiError apiError = (exception != null ? ApiError.builderFromThrowable(exception).prefixMessage(suppliedMsg) : ApiError.builder().message(fullMsg==null ? "" : fullMsg)) .errorCode(status).build(); // including a Throwable is the only way to include a message with the WebApplicationException - ugly! throw new WebApplicationException( exception==null ? new Throwable(apiError.toString()) : suppliedMsg==null ? exception : new PropagatedRuntimeException(suppliedMsg, exception), apiError.asJsonResponse()); }
@Test public void test12CollapsePropagatedCompoundConcMod() throws Exception { RuntimeException e = new PropagatedRuntimeException("test1", new ExecutionException(Exceptions.create(MutableSet.of(new ConcurrentModificationException("test2"), new ConcurrentModificationException("test3"))))); assert12StandardChecks(e, true); assertContains(e, "ConcurrentModification"); }
} catch (Throwable e) { Exceptions.propagateIfFatal(e); otherProblemsFromTransformers.add(new PropagatedRuntimeException("Transformer for "+t.getShortDescription()+" gave an error creating this plan: ", Exceptions.collapseText(e), e));
public void handleException(Throwable throwable, Object details) { if (throwable instanceof InterruptedException) throw new RuntimeInterruptedException((InterruptedException) throwable); if (throwable instanceof RuntimeInterruptedException) throw (RuntimeInterruptedException) throwable; if (details instanceof CatalogItem) { if (((CatalogItem<?,?>)details).getCatalogItemId() != null) { details = ((CatalogItem<?,?>)details).getCatalogItemId(); } } PropagatedRuntimeException wrap = new PropagatedRuntimeException("Error loading catalog item "+details, throwable); log.warn(Exceptions.collapseText(wrap)); log.debug("Trace for: "+wrap, wrap); ((ManagementContextInternal)getManagementContext()).errors().add(wrap); if (isStartingUp && failOnStartupErrors) { throw new FatalRuntimeException("Unable to load catalog item "+details, wrap); } }