Example usage for java.lang Throwable setStackTrace

List of usage examples for java.lang Throwable setStackTrace

Introduction

In this page you can find the example usage for java.lang Throwable setStackTrace.

Prototype

public void setStackTrace(StackTraceElement[] stackTrace) 

Source Link

Document

Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.

Usage

From source file:org.openspaces.test.client.executor.ExecutorUtils.java

/**
 * Strip stack trace of provided {@link Throwable} object up to supplied classname <b>and</b>
 * method name. This method is useful when you wish to hide internal stackTrace.<br> This method
 * scans the {@link Throwable#getStackTrace()} and removes all {@link StackTraceElement} up to
 * supplied classname and methodName. The Throwable's cause is also scanned in a
 * <i>recursive</i> manner. <p> <u>NOTE</u>: If the provided classname and method was not found
 * in the stackTrace, the {@link Throwable} stackTrace stays unmodified.
 *
 * <pre>//from  w w w. ja va 2  s  .  com
 * For example:
 * Original stackTrace:
 * java.lang.Exception: Example stack trace...
 * at test.TestSTrace.applCall3(Test.java:926)
 * at test.TestSTrace.applCall2(Test.java:921)
 * at test.TestSTrace.applCall1(Test.java:916)
 * at test.TestSTrace.startApplCall(Test.java:912)
 * at test.TestSTrace.internalCall3(Test.java:941)
 * at test.TestSTrace.internalCall2(Test.java:936)
 * at test.TestSTrace.internalCall1(Test.java:931)
 * at test.TestSTrace.main(Test.java:977)
 *
 * TGridHelper.stripStackTrace(throwable, "test.TestSTrace", "startApplCall");
 * throwable.printStackTrace();
 *
 * After:
 * java.lang.Exception: Example stack trace...
 * at test.TestSTrace.applCall3(Test.java:941)
 * at test.TestSTrace.applCall2(Test.java:936)
 * at test.TestSTrace.applCall1(Test.java:931)
 * at test.TestSTrace.startApplCall(Test.java:912)
 * </pre>
 *
 * @param ex         the throwable object to strip stack trace.
 * @param className  strip stackTrace up to classname.
 * @param methodName strip stackTrace up to methodName.
 */
public static void stripStackTrace(Throwable ex, String className, String methodName) {
    boolean found = false;
    StackTraceElement[] ste = ex.getStackTrace();
    List<StackTraceElement> stList = asList(ste);
    for (int i = stList.size() - 1; i >= 0; i--) {
        StackTraceElement traceList = stList.get(i);
        String traceClassName = traceList.getClassName();
        String traceMethodName = traceList.getMethodName();

        /* only if classname and method are equals with StackTraceElement */
        if (!(traceClassName.equals(className) && traceMethodName.equals(methodName)))
            stList.remove(i);
        else {
            found = true;
            break;
        }
    }

    /* replace only if provided classname and method was found the the stackTrace */
    if (found)
        ex.setStackTrace(stList.toArray(new StackTraceElement[stList.size()]));

    /* recursive call on all causes */
    Throwable cause = ex.getCause();
    if (cause != null)
        stripStackTrace(cause, className, methodName);
}

From source file:com.infinities.skyport.async.impl.AsyncHandler.java

private Exception throwCause(Exception e, boolean combineStackTraces) throws Exception {
    Throwable cause = e.getCause();
    if (cause == null) {
        throw e;/* w w  w .  j  a v  a2 s. com*/
    }
    if (combineStackTraces) {
        StackTraceElement[] combined = ObjectArrays.concat(cause.getStackTrace(), e.getStackTrace(),
                StackTraceElement.class);
        cause.setStackTrace(combined);
    }
    if (cause instanceof Exception) {
        throw (Exception) cause;
    }
    if (cause instanceof Error) {
        throw (Error) cause;
    }
    // The cause is a weird kind of Throwable, so throw the outer
    // exception.
    throw e;
}

From source file:org.rhq.core.pc.inventory.AvailabilityProxy.java

/**
 * Returns the current or most currently reported availability. If
 * {@link AvailabilityType#UNKNOWN} is returned, then the availability is
 * being computed.//ww  w  .ja  v a2  s . co  m
 *
 * @throws TimeoutException
 *             if an async check exceeds AVAIL_ASYNC_TIMEOUT
 */
@Override
public AvailabilityType getAvailability() {
    AvailabilityType avail = UNKNOWN;

    try {
        // If the avail check timed out, or if we are not attempting synchronous checks (due to
        // exceeding the consecutive timeout limit) then the future will exist.
        if (availabilityFuture != null) {
            if (availabilityFuture.isDone()) {
                // hold onto and report the last known value if necessary
                avail = availabilityFuture.get();

            } else {
                // We are still waiting on the previously submitted async avail check - let's just return
                // the last one we got. Note that if the future is not done after a large amount of time,
                // then it means this thread could somehow be hung or otherwise stuck and not returning. Not good.
                // In this case, throw a detailed exception to the avail checker.
                long elapsedTime = System.currentTimeMillis() - lastSubmitTime;
                if (elapsedTime > getAsyncTimeout()) {

                    Throwable t = new Throwable();
                    if (current != null) {
                        t.setStackTrace(current.getStackTrace());
                    }
                    String msg = "Availability check ran too long [" + elapsedTime + "ms], canceled for ["
                            + this.resourceContainer
                            + "]; Stack trace includes the timed out thread's stack trace.";
                    availabilityFuture.cancel(true);

                    // try again, maybe the situation will resolve in time for the next check
                    availabilityFuture = this.resourceContainer.submitAvailabilityCheck(this);
                    lastSubmitTime = System.currentTimeMillis();

                    throw new TimeoutException(msg, t);
                } else {
                    return getLastAvailabilityType();
                }
            }
        }

        // request a thread to do an avail check
        availabilityFuture = this.resourceContainer.submitAvailabilityCheck(this);
        lastSubmitTime = System.currentTimeMillis();

        // if we have exceeded the timeout too many times in a row assume that this is a slow
        // resource and stop performing synchronous checks, which would likely fail to return fast enough anyway.
        if (availSyncConsecutiveTimeouts < getSyncTimeoutLimit()) {
            // attempt to get availability synchronously
            avail = availabilityFuture.get(getSyncTimeout(), TimeUnit.MILLISECONDS);

            // success (failure will throw exception)
            availSyncConsecutiveTimeouts = 0;
            availabilityFuture = null;

        } else if (availSyncConsecutiveTimeouts == getSyncTimeoutLimit()) {
            // log one time that we are disabling synchronous checks for this resource
            ++availSyncConsecutiveTimeouts;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Disabling synchronous availability collection for [" + resourceContainer + "]; ["
                        + getSyncTimeoutLimit() + "] consecutive timeouts exceeding [" + getSyncTimeout()
                        + "ms]");
            }
        }
    } catch (InterruptedException e) {
        LOG.debug("InterruptedException; shut down is (likely) in progress.");
        availabilityFuture.cancel(true);
        availabilityFuture = null;
        Thread.currentThread().interrupt();
        return UNKNOWN;

    } catch (ExecutionException e) {
        availabilityFuture = null; // undefine, so in next run new (no longer failed) instance is scheduled
        throw new RuntimeException("Availability check failed : " + e.getCause().getMessage(), e.getCause());

    } catch (java.util.concurrent.TimeoutException e) {
        // failed to get avail synchronously. next call to the future will return availability (we hope)
        ++availSyncConsecutiveTimeouts;
    }

    return processAvail(avail);
}

From source file:org.eclipse.epp.internal.logging.aeri.ui.LogListenerTest.java

@Test
public void testNoAcceptingOtherPackages() {
    Throwable t = new RuntimeException();
    t.fillInStackTrace();/*from www  .  ja va  2s  .  c om*/
    StackTraceElement[] stackTrace = t.getStackTrace();
    stackTrace[0] = new StackTraceElement("any.third.party.Clazz", "thirdPartyMethod", "Clazz.java", 42);
    t.setStackTrace(stackTrace);
    Status status = new Status(IStatus.ERROR, TEST_PLUGIN_ID, "Error Message", t);

    configuration.setAcceptOtherPackages(false);

    sut.logging(status, "");
    verifyNoErrorReportLogged();
}

From source file:com.mirth.connect.server.controllers.DefaultCodeTemplateController.java

private Throwable convertUpdateCause(Throwable t) {
    if (t instanceof ControllerException) {
        if (t.getCause() != null) {
            t = t.getCause();//from w  w w .  j a v  a  2  s  .  c  om
        } else {
            StackTraceElement[] stackTrace = t.getStackTrace();
            t = new Exception(t.getMessage());
            t.setStackTrace(stackTrace);
        }
    }

    return t;
}

From source file:org.codehaus.groovy.grails.exceptions.DefaultStackTraceFilterer.java

public Throwable filter(Throwable source) {
    if (shouldFilter) {
        StackTraceElement[] trace = source.getStackTrace();
        List<StackTraceElement> newTrace = filterTraceWithCutOff(trace, cutOffPackage);

        if (newTrace.isEmpty()) {
            // filter with no cut-off so at least there is some trace
            newTrace = filterTraceWithCutOff(trace, null);
        }//from  ww  w. j  a  v  a2  s .c  o m

        // Only trim the trace if there was some application trace on the stack
        // if not we will just skip sanitizing and leave it as is
        if (!newTrace.isEmpty()) {
            // We don't want to lose anything, so log it
            STACK_LOG.error(FULL_STACK_TRACE_MESSAGE, source);
            StackTraceElement[] clean = new StackTraceElement[newTrace.size()];
            newTrace.toArray(clean);
            source.setStackTrace(clean);
        }
    }
    return source;
}

From source file:hudson.FunctionsTest.java

@Issue("JDK-6507809")
@Test/*from  ww  w  .  ja v a  2s .c om*/
public void printThrowable() throws Exception {
    // Basics: a single exception. No change.
    assertPrintThrowable(new Stack("java.lang.NullPointerException: oops", "p.C.method1:17", "m.Main.main:1"),
            "java.lang.NullPointerException: oops\n" + "\tat p.C.method1(C.java:17)\n"
                    + "\tat m.Main.main(Main.java:1)\n",
            "java.lang.NullPointerException: oops\n" + "\tat p.C.method1(C.java:17)\n"
                    + "\tat m.Main.main(Main.java:1)\n");
    // try {} catch (Exception x) {throw new IllegalStateException(x);}
    assertPrintThrowable(
            new Stack("java.lang.IllegalStateException: java.lang.NullPointerException: oops", "p.C.method1:19",
                    "m.Main.main:1")
                            .cause(new Stack("java.lang.NullPointerException: oops", "p.C.method2:23",
                                    "p.C.method1:17", "m.Main.main:1")),
            "java.lang.IllegalStateException: java.lang.NullPointerException: oops\n"
                    + "\tat p.C.method1(C.java:19)\n" + "\tat m.Main.main(Main.java:1)\n"
                    + "Caused by: java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "\t... 1 more\n",
            "java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "Caused: java.lang.IllegalStateException\n"
                    + "\tat p.C.method1(C.java:19)\n" + "\tat m.Main.main(Main.java:1)\n");
    // try {} catch (Exception x) {throw new IllegalStateException("more info");}
    assertPrintThrowable(
            new Stack("java.lang.IllegalStateException: more info", "p.C.method1:19", "m.Main.main:1")
                    .cause(new Stack("java.lang.NullPointerException: oops", "p.C.method2:23", "p.C.method1:17",
                            "m.Main.main:1")),
            "java.lang.IllegalStateException: more info\n" + "\tat p.C.method1(C.java:19)\n"
                    + "\tat m.Main.main(Main.java:1)\n" + "Caused by: java.lang.NullPointerException: oops\n"
                    + "\tat p.C.method2(C.java:23)\n" + "\tat p.C.method1(C.java:17)\n" + "\t... 1 more\n",
            "java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "Caused: java.lang.IllegalStateException: more info\n"
                    + "\tat p.C.method1(C.java:19)\n" + "\tat m.Main.main(Main.java:1)\n");
    // try {} catch (Exception x) {throw new IllegalStateException("more info: " + x);}
    assertPrintThrowable(
            new Stack("java.lang.IllegalStateException: more info: java.lang.NullPointerException: oops",
                    "p.C.method1:19", "m.Main.main:1")
                            .cause(new Stack("java.lang.NullPointerException: oops", "p.C.method2:23",
                                    "p.C.method1:17", "m.Main.main:1")),
            "java.lang.IllegalStateException: more info: java.lang.NullPointerException: oops\n"
                    + "\tat p.C.method1(C.java:19)\n" + "\tat m.Main.main(Main.java:1)\n"
                    + "Caused by: java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "\t... 1 more\n",
            "java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "Caused: java.lang.IllegalStateException: more info\n"
                    + "\tat p.C.method1(C.java:19)\n" + "\tat m.Main.main(Main.java:1)\n");
    // Synthetic stack showing an exception made elsewhere, such as happens with hudson.remoting.Channel.attachCallSiteStackTrace.
    Throwable t = new Stack("remote.Exception: oops", "remote.Place.method:17", "remote.Service.run:9");
    StackTraceElement[] callSite = new Stack("wrapped.Exception", "local.Side.call:11", "local.Main.main:1")
            .getStackTrace();
    StackTraceElement[] original = t.getStackTrace();
    StackTraceElement[] combined = new StackTraceElement[original.length + 1 + callSite.length];
    System.arraycopy(original, 0, combined, 0, original.length);
    combined[original.length] = new StackTraceElement(".....", "remote call", null, -2);
    System.arraycopy(callSite, 0, combined, original.length + 1, callSite.length);
    t.setStackTrace(combined);
    assertPrintThrowable(t,
            "remote.Exception: oops\n" + "\tat remote.Place.method(Place.java:17)\n"
                    + "\tat remote.Service.run(Service.java:9)\n" + "\tat ......remote call(Native Method)\n"
                    + "\tat local.Side.call(Side.java:11)\n" + "\tat local.Main.main(Main.java:1)\n",
            "remote.Exception: oops\n" + "\tat remote.Place.method(Place.java:17)\n"
                    + "\tat remote.Service.run(Service.java:9)\n" + "\tat ......remote call(Native Method)\n"
                    + "\tat local.Side.call(Side.java:11)\n" + "\tat local.Main.main(Main.java:1)\n");
    // Same but now using a cause on the remote side.
    t = new Stack("remote.Wrapper: remote.Exception: oops", "remote.Place.method2:19", "remote.Service.run:9")
            .cause(new Stack("remote.Exception: oops", "remote.Place.method1:11", "remote.Place.method2:17",
                    "remote.Service.run:9"));
    callSite = new Stack("wrapped.Exception", "local.Side.call:11", "local.Main.main:1").getStackTrace();
    original = t.getStackTrace();
    combined = new StackTraceElement[original.length + 1 + callSite.length];
    System.arraycopy(original, 0, combined, 0, original.length);
    combined[original.length] = new StackTraceElement(".....", "remote call", null, -2);
    System.arraycopy(callSite, 0, combined, original.length + 1, callSite.length);
    t.setStackTrace(combined);
    assertPrintThrowable(t,
            "remote.Wrapper: remote.Exception: oops\n" + "\tat remote.Place.method2(Place.java:19)\n"
                    + "\tat remote.Service.run(Service.java:9)\n" + "\tat ......remote call(Native Method)\n"
                    + "\tat local.Side.call(Side.java:11)\n" + "\tat local.Main.main(Main.java:1)\n"
                    + "Caused by: remote.Exception: oops\n" + "\tat remote.Place.method1(Place.java:11)\n"
                    + "\tat remote.Place.method2(Place.java:17)\n"
                    + "\tat remote.Service.run(Service.java:9)\n",
            "remote.Exception: oops\n" + "\tat remote.Place.method1(Place.java:11)\n"
                    + "\tat remote.Place.method2(Place.java:17)\n" + "\tat remote.Service.run(Service.java:9)\n"
                    + // we do not know how to elide the common part in this case
                    "Caused: remote.Wrapper\n" + "\tat remote.Place.method2(Place.java:19)\n"
                    + "\tat remote.Service.run(Service.java:9)\n" + "\tat ......remote call(Native Method)\n"
                    + "\tat local.Side.call(Side.java:11)\n" + "\tat local.Main.main(Main.java:1)\n");
    // Suppressed exceptions:
    assertPrintThrowable(
            new Stack("java.lang.IllegalStateException: java.lang.NullPointerException: oops", "p.C.method1:19",
                    "m.Main.main:1")
                            .cause(new Stack("java.lang.NullPointerException: oops", "p.C.method2:23",
                                    "p.C.method1:17", "m.Main.main:1"))
                            .suppressed(
                                    new Stack("java.io.IOException: could not close", "p.C.close:99",
                                            "p.C.method1:18", "m.Main.main:1"),
                                    new Stack("java.io.IOException: java.lang.NullPointerException",
                                            "p.C.flush:77", "p.C.method1:18", "m.Main.main:1")
                                                    .cause(new Stack("java.lang.NullPointerException",
                                                            "p.C.findFlushee:70", "p.C.flush:75",
                                                            "p.C.method1:18", "m.Main.main:1"))),
            "java.lang.IllegalStateException: java.lang.NullPointerException: oops\n"
                    + "\tat p.C.method1(C.java:19)\n" + "\tat m.Main.main(Main.java:1)\n"
                    + "\tSuppressed: java.io.IOException: could not close\n" + "\t\tat p.C.close(C.java:99)\n"
                    + "\t\tat p.C.method1(C.java:18)\n" + "\t\t... 1 more\n"
                    + "\tSuppressed: java.io.IOException: java.lang.NullPointerException\n"
                    + "\t\tat p.C.flush(C.java:77)\n" + "\t\tat p.C.method1(C.java:18)\n" + "\t\t... 1 more\n"
                    + "\tCaused by: java.lang.NullPointerException\n" + "\t\tat p.C.findFlushee(C.java:70)\n"
                    + "\t\tat p.C.flush(C.java:75)\n" + "\t\t... 2 more\n"
                    + "Caused by: java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "\t... 1 more\n",
            "java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "Also:   java.io.IOException: could not close\n"
                    + "\t\tat p.C.close(C.java:99)\n" + "\t\tat p.C.method1(C.java:18)\n"
                    + "Also:   java.lang.NullPointerException\n" + "\t\tat p.C.findFlushee(C.java:70)\n"
                    + "\t\tat p.C.flush(C.java:75)\n" + "\tCaused: java.io.IOException\n"
                    + "\t\tat p.C.flush(C.java:77)\n" + "\t\tat p.C.method1(C.java:18)\n"
                    + "Caused: java.lang.IllegalStateException\n" + "\tat p.C.method1(C.java:19)\n"
                    + "\tat m.Main.main(Main.java:1)\n");
    // Custom printStackTrace implementations:
    assertPrintThrowable(new Throwable() {
        @Override
        public void printStackTrace(PrintWriter s) {
            s.println("Some custom exception");
        }
    }, "Some custom exception\n", "Some custom exception\n");
    // Circular references:
    Stack stack1 = new Stack("p.Exc1", "p.C.method1:17");
    Stack stack2 = new Stack("p.Exc2", "p.C.method2:27");
    stack1.cause(stack2);
    stack2.cause(stack1);
    assertPrintThrowable(stack1,
            "p.Exc1\n" + "\tat p.C.method1(C.java:17)\n" + "Caused by: p.Exc2\n"
                    + "\tat p.C.method2(C.java:27)\n" + "\t[CIRCULAR REFERENCE:p.Exc1]\n",
            "<cycle to p.Exc1>\n" + "Caused: p.Exc2\n" + "\tat p.C.method2(C.java:27)\n" + "Caused: p.Exc1\n"
                    + "\tat p.C.method1(C.java:17)\n");
}

From source file:com.seleniumtests.reporter.SeleniumTestsReporter.java

public void afterInvocation(final IInvokedMethod method, final ITestResult result) {
    Reporter.setCurrentTestResult(result);

    // Handle Soft CustomAssertion
    if (method.isTestMethod()) {
        final List<Throwable> verificationFailures = CustomAssertion.getVerificationFailures();

        final int size = verificationFailures.size();
        if (size == 0) {
            return;
        } else if (result.getStatus() == TestResult.FAILURE) {
            return;
        }//from  www  . ja  v  a  2s.c  om

        result.setStatus(TestResult.FAILURE);

        if (size == 1) {
            result.setThrowable(verificationFailures.get(0));
        } else {

            // create failure message with all failures and stack traces barring last failure)
            final StringBuilder failureMessage = new StringBuilder("!!! Many Test Failures (").append(size)
                    .append(")\n");
            for (int i = 0; i < size - 1; i++) {
                failureMessage.append("Failure ").append(i + 1).append(" of ").append(size).append("\n");

                final Throwable t = verificationFailures.get(i);
                final String fullStackTrace = Utils.stackTrace(t, false)[1];
                failureMessage.append(fullStackTrace).append("\n");
            }

            // final failure
            final Throwable last = verificationFailures.get(size - 1);
            failureMessage.append("Failure ").append(size).append(" of ").append(size).append(":n");
            failureMessage.append(last.toString());

            // set merged throwable
            final Throwable merged = new Throwable(failureMessage.toString());
            merged.setStackTrace(last.getStackTrace());

            result.setThrowable(merged);
        }
    }
}

From source file:org.auraframework.integration.test.util.WebDriverTestCase.java

/**
 * Gather up useful info to add to a test failure. try to get
 * <ul>/*  w w  w  . j a va 2  s . c o m*/
 * <li>any client js errors</li>
 * <li>last known js test function</li>
 * <li>running/waiting</li>
 * <li>a screenshot</li>
 * </ul>
 *
 * @param originalErr the test failure
 * @throws Throwable a new AssertionFailedError or UnexpectedError with the original and additional info
 */
private Throwable addAuraInfoToTestFailure(Throwable originalErr) {
    StringBuffer description = new StringBuffer();
    if (originalErr != null) {
        String msg = originalErr.getMessage();
        if (msg != null) {
            description.append(msg);
        }
    }

    description.append(String.format("\nBrowser: %s", currentBrowserType));
    if (getAuraUITestingUtil() != null) {
        description.append("\nUser-Agent: " + getAuraUITestingUtil().getUserAgent());
    }
    if (currentDriver == null) {
        description.append("\nTest failed before WebDriver was initialized");
    } else {

        if (this instanceof PerfExecutorTestCase) {
            JSONArray json = this.getLastCollectedMetrics();
            description.append("\nPerfMetrics: " + json + ';');
        }

        description.append("\nWebDriver: " + currentDriver);
        description.append("\nJS state: ");
        try {
            String dump = (String) getAuraUITestingUtil()
                    .getRawEval("return (window.$A && $A.test && $A.test.getDump())||'';");
            if (dump.isEmpty()) {
                description.append("no errors detected");
            } else {
                description.append(dump);
            }
        } catch (Throwable t) {
            description.append(t.getMessage());
        }

        String screenshotsDirectory = System.getProperty("screenshots.directory");
        if (screenshotsDirectory != null) {
            String screenshot = null;
            TakesScreenshot ts = (TakesScreenshot) currentDriver;
            try {
                screenshot = ts.getScreenshotAs(OutputType.BASE64);
            } catch (WebDriverException e) {
                description.append(String.format("%nScreenshot: {capture error: %s}", e.getMessage()));
            }

            if (screenshot != null) {
                String fileName = getClass().getName() + "." + getName() + "_" + currentBrowserType + ".png";
                try {
                    File path = new File(screenshotsDirectory + "/" + fileName);
                    path.getParentFile().mkdirs();
                    byte[] bytes = Base64.decodeBase64(screenshot.getBytes());
                    FileOutputStream fos = new FileOutputStream(path);
                    fos.write(bytes);
                    fos.close();
                    String baseUrl = System.getProperty("screenshots.baseurl");
                    description.append(String.format("%nScreenshot: %s/%s", baseUrl, fileName));
                } catch (Throwable t) {
                    description.append(String.format("%nScreenshot: {save error: %s}", t.getMessage()));
                }
            }
        }

        try {
            description.append("\nApplication cache status: ");
            description.append(getAuraUITestingUtil().getRawEval(
                    "var cache=window.applicationCache;return (cache===undefined || cache===null)?'undefined':cache.status;")
                    .toString());
        } catch (Exception ex) {
            description.append("error calculating status: " + ex);
        }
        description.append("\n");
        if (SauceUtil.areTestsRunningOnSauce()) {
            String linkToJob = SauceUtil.getLinkToPublicJobInSauce(currentDriver);
            description.append("\nSauceLabs-recording: ");
            description.append((linkToJob != null) ? linkToJob : "{not available}");
        }
    }

    // replace original exception with new exception with additional info
    Throwable newFailure;
    if (originalErr instanceof AssertionFailedError) {
        newFailure = new AssertionFailedError(description.toString());
    } else {
        description.insert(0, originalErr.getClass() + ": ");
        newFailure = new UnexpectedError(description.toString(), originalErr.getCause());
    }
    newFailure.setStackTrace(originalErr.getStackTrace());
    return newFailure;
}

From source file:org.auraframework.test.WebDriverTestCase.java

/**
 * Gather up useful info to add to a test failure. try to get
 * <ul>/*from   w w  w.  j  a  va 2  s .  c o m*/
 * <li>any client js errors</li>
 * <li>last known js test function</li>
 * <li>running/waiting</li>
 * <li>a screenshot</li>
 * </ul>
 * 
 * @param originalErr the test failure
 * @throws Throwable a new AssertionFailedError or UnexpectedError with the original and additional info
 */
private Throwable addAuraInfoToTestFailure(Throwable originalErr) {
    StringBuffer description = new StringBuffer();
    if (originalErr != null) {
        String msg = originalErr.getMessage();
        if (msg != null) {
            description.append(msg);
        }
    }
    description.append(String.format("\nBrowser: %s", currentBrowserType));
    if (auraUITestingUtil != null) {
        description.append("\nUser-Agent: " + auraUITestingUtil.getUserAgent());
    }
    if (currentDriver == null) {
        description.append("\nTest failed before WebDriver was initialized");
    } else {
        description.append("\nWebDriver: " + currentDriver);
        description.append("\nJS state: ");
        try {
            String dump = (String) auraUITestingUtil
                    .getRawEval("return (window.$A && $A.test && $A.test.getDump())||'';");
            if (dump.isEmpty()) {
                description.append("no errors detected");
            } else {
                description.append(dump);
            }
        } catch (Throwable t) {
            description.append(t.getMessage());
        }

        String screenshotsDirectory = System.getProperty("screenshots.directory");
        if (screenshotsDirectory != null) {
            String img = getBase64EncodedScreenshot(originalErr, true);
            if (img == null) {
                description.append("\nScreenshot: {not available}");
            } else {
                String fileName = getClass().getName() + "." + getName() + "_" + currentBrowserType + ".png";
                File path = new File(screenshotsDirectory + "/" + fileName);
                try {
                    path.getParentFile().mkdirs();
                    byte[] bytes = Base64.decodeBase64(img.getBytes());
                    FileOutputStream fos = new FileOutputStream(path);
                    fos.write(bytes);
                    fos.close();
                    String baseUrl = System.getProperty("screenshots.baseurl");
                    description.append(String.format("%nScreenshot: %s/%s", baseUrl, fileName));
                } catch (Throwable t) {
                    description.append(String.format("%nScreenshot: {save error: %s}", t.getMessage()));
                }
            }
        }

        try {
            description.append("\nApplication cache status: ");
            description.append(auraUITestingUtil.getRawEval(
                    "var cache=window.applicationCache;return (cache===undefined || cache===null)?'undefined':cache.status;")
                    .toString());
        } catch (Exception ex) {
            description.append("error calculating status: " + ex);
        }
        description.append("\n");
        if (SauceUtil.areTestsRunningOnSauce()) {
            String linkToJob = SauceUtil.getLinkToPublicJobInSauce(currentDriver);
            description.append("\nSauceLabs-recording: ");
            description.append((linkToJob != null) ? linkToJob : "{not available}");
        }
    }

    // replace original exception with new exception with additional info
    Throwable newFailure;
    if (originalErr instanceof AssertionFailedError) {
        newFailure = new AssertionFailedError(description.toString());
    } else {
        description.insert(0, originalErr.getClass() + ": ");
        newFailure = new UnexpectedError(description.toString(), originalErr.getCause());
    }
    newFailure.setStackTrace(originalErr.getStackTrace());
    return newFailure;
}