[New] Added ExceptionHelper.getExceptionMessageWithCauses() and tests

This commit is contained in:
Robert von Burg 2015-10-02 08:19:07 +02:00
parent 67d1052fd3
commit f59f4c5c0f
2 changed files with 76 additions and 19 deletions

View File

@ -40,6 +40,29 @@ public class ExceptionHelper {
return StringHelper.isEmpty(t.getMessage()) ? t.getClass().getName() : t.getMessage();
}
/**
* <p>
* Returns a message for the given {@link Throwable}
* </p>
*
* <p>
* A {@link NullPointerException} only has <code>null</code> as the message so this methods returns the class name
* in such a case
* </p>
*
* @param t
* @return
*/
public static String getExceptionMessageWithCauses(Throwable t) {
if (t.getCause() == null) {
return getExceptionMessage(t);
}
String root = getExceptionMessageWithCauses(t.getCause());
return getExceptionMessage(t) + "\n" + root;
}
/**
* Formats the given {@link Throwable}'s stack trace to a string
*
@ -64,24 +87,12 @@ public class ExceptionHelper {
* @return a string representation of the given {@link Throwable}'s messages including causes
*/
public static String formatExceptionMessage(Throwable t) {
StringBuilder sb = new StringBuilder();
sb.append(t.getMessage());
appendCause(sb, t);
return sb.toString();
if (t.getCause() == null) {
return getExceptionMessage(t);
}
String root = formatExceptionMessage(t.getCause());
return getExceptionMessage(t) + "\ncause:\n" + root;
}
private static void appendCause(StringBuilder sb, Throwable e) {
Throwable cause = e.getCause();
if (cause == null)
return;
sb.append("\n");
sb.append("cause:\n");
sb.append(cause.getMessage());
if (cause.getCause() != null)
appendCause(sb, cause.getCause());
}
}

View File

@ -0,0 +1,46 @@
package ch.eitchnet.utils.helper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ExceptionHelperTest {
@Test
public void shouldGetExceptionMsg() {
Exception e = nestedException();
assertEquals("Third", ExceptionHelper.getExceptionMessage(e));
assertEquals("Third\nSecond\nFirst", ExceptionHelper.getExceptionMessageWithCauses(e));
}
@Test
public void shouldFormatException() {
Exception e = nestedException();
String formatException = ExceptionHelper.formatException(e);
assertTrue(formatException.contains("java.lang.RuntimeException: First"));
assertTrue(formatException.contains("java.lang.RuntimeException: Second"));
assertTrue(formatException.contains("java.lang.RuntimeException: Third"));
formatException = ExceptionHelper.formatExceptionMessage(e);
assertEquals("Third\ncause:\nSecond\ncause:\nFirst", formatException);
}
private Exception nestedException() {
try {
try {
try {
throw new RuntimeException("First");
} catch (Exception e) {
throw new RuntimeException("Second", e);
}
} catch (Exception e) {
throw new RuntimeException("Third", e);
}
} catch (Exception e) {
return e;
}
}
}