I am looking for a elegant solution to this. I am new to Spring framework. I have a method:
public String getStringProperty(String property) {
Object value = SomeWrapper.getPropertyValue(property);
return (value != null) ? String.valueOf(value) : "";
}
The immediate upstream method is:
public String getValueForHeader(String header) {
return getStringProperty(LOOKUP_TABLE.get(header));
}
Where LOOKUP_TABLE
is an ImmutableMap (google guava). An example representation of it:
private final ImmutableMap<String, String> LOOKUP_TABLE = ImmutableMap.<String, String>builder()
.put(LogHeaders.Phone, "Person.phone")
.put(LogHeaders.Address, "Person.personal.address")
.put(LogHeaders.Email, "Person.billing.contact.primary.email")
.put(LogHeaders.Ip, "Person.ip")
.build();
So, when I call getStringProperty
method with property
"Person.billing.contact.primary.email"
I get a ""
String. My aim here is to return empty String when some property does not exist. For example if "Person.billing.contact.primary.email"
does not have "email"
set in address an empty String is returned. Now if "contact"
or "primary"
doesis not existset I would get a NullValueInNestedPathException
but I should return an empty String.
One way to deal with this is to introduce the try catch lock in this method and have the catch block return empty string.
public String getStringProperty(String property) {
try {
Object value = transactionWrapper.getPropertyValue(property);
return (value != null) ? String.valueOf(value) : "";
} catch (NullValueInNestedPathException e) {
return "";
} catch (NotReadablePropertyException nr) {
LOGGER.error("Invalid property {} ", property);
return "!invalid property!";
}
}
The NotReadablePropertyException
is to warn me when I am trying to get some property
which does not exist (or getter for that property is not readable).
The other solution could be to throw
same exception and let methods upstream worry.
Is there some alternative, elegant way to handle this inside my getStringProperty()
method ?