Skip to content

Instantly share code, notes, and snippets.

@Syhids
Last active November 6, 2015 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Syhids/9dc377d68f1ce427d8c7 to your computer and use it in GitHub Desktop.
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
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