/** * Truncates the @{Throwable}'s stack trace to contain only user code, removing all frames below. * * <p>This is to remove infrastructure noise below user code entry point. We do this by finding * common stack frames between the throwable's captured stack and that of the current thread. */ private void truncateStackTrace(Throwable t) { StackTraceElement[] currentStack = Thread.currentThread().getStackTrace(); StackTraceElement[] throwableStack = t.getStackTrace(); int currentStackSize = currentStack.length; int throwableStackSize = throwableStack.length; if (throwableStackSize == 0) { // Nothing to truncate. return; } int commonFrames = 0; while (framesEqual( currentStack[currentStackSize - commonFrames - 1], throwableStack[throwableStackSize - commonFrames - 1])) { commonFrames++; if (commonFrames >= Math.min(currentStackSize, throwableStackSize)) { break; } } StackTraceElement[] truncatedStack = Arrays.copyOfRange(throwableStack, 0, throwableStackSize - commonFrames); t.setStackTrace(truncatedStack); }