Hey folks,
Here's a possible solution that I whipped up to solve NullPointerExceptions coming out of otherwise perfectly good ValueProviders.
Code:
import com.google.gwt.core.client.JavaScriptException;
import com.sencha.gxt.core.client.ValueProvider;
/**
* The purpose of this class is to wrap a value provider but handle NullPointerExceptions gracefully.
*
* Note: JavsScript doesn't throw java.lang.NullPointerExceptions (that's a Java thing) so this method technicallly catches both NullPointerException
* (for hosted mode), and JavaScriptExceptions (for production mode).
*/
public class HandleNullValueProvider<T, V> implements ValueProvider<T, V> {
private ValueProvider<T,V> innerValueProvider;
private V defaultValue;
/**
* @param innerValueProvider The provider to delegate calls to.
* @param defaultValue The value to provide if innerValueProvider should throw an exception
*/
public HandleNullValueProvider(ValueProvider<T, V> innerValueProvider, V defaultValue) {
this.innerValueProvider = innerValueProvider;
this.defaultValue = defaultValue;
}
@Override
public V getValue(T object) {
try {
return innerValueProvider.getValue(object);
} catch (NullPointerException e) {
return defaultValue;
} catch (JavaScriptException e) {
return defaultValue;
}
}
@Override
public void setValue(T object, V value) {
try {
innerValueProvider.setValue(object, value);
} catch (NullPointerException ignored) {
} catch (JavaScriptException ignored) {
}
}
@Override
public String getPath() {
return innerValueProvider.getPath();
}
}
Wherever you would normally put in a ValueProvider, you replace it with this:
Code:
new HandleNullValueProvider<Person, Long>(properties.companyId(), 0L)
If Person.getCompanyId() ever return null, this ValueProvider will return the default, which is 0.
P.S. I think it would be great if Sencha GXT included a class like this (or another mechanism to solve null values). It's painful to write custom ValueProviders for every value that *might* be null some day.