Last active
November 6, 2015 12:59
-
-
Save Syhids/9dc377d68f1ce427d8c7 to your computer and use it in GitHub Desktop.
Preconditions with better stacktraces for crash reporting tools. Credits to @pyricau. More info at http://www.slideshare.net/pyricau/crash-fast-furious
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Preconditions { | |
public static <T> T checkNotNull(T t, String name) { | |
if (t == null) { | |
throw withPreconditionsTraceRemoved(new NullPointerException(name + " must not be null")); | |
} | |
return t; | |
} | |
public static <T extends CharSequence> T nonBlank(T value, String name) { | |
if (isBlank(value)) { | |
throw withPreconditionsTraceRemoved(new IllegalArgumentException(name + " must not be blank")); | |
} | |
return value; | |
} | |
private static <T extends CharSequence> boolean isBlank(T value) { | |
if (value == null || value.length() == 0) | |
return true; | |
for (int i = 0; i < value.length(); i++) { | |
if (!Character.isWhitespace(value.charAt(i))) { | |
return false; | |
} | |
} | |
return true; | |
} | |
private static <T extends Exception> T withPreconditionsTraceRemoved(T exception) { | |
StackTraceElement[] sourceStack = exception.getStackTrace(); | |
StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1]; | |
System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length); | |
exception.setStackTrace(updatedStack); | |
return exception; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment