I would like code not throws exception when java code load enum value from mongo that not exists in enum code
Exemple :
java.lang.IllegalArgumentException: No enum constant fr.myapp.type.OrderOptionEnum.TELEPHONE
at java.lang.Enum.valueOf(Enum.java:238)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.getPotentiallyConvertedSimpleRead(MappingMongoConverter.java:819)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readCollectionOrArray(MappingMongoConverter.java:909)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readValue(MappingMongoConverter.java:1184)
Because TELEPHONE not existe in OrderOptionEnum
I juste want the code return null value
Any idea ?
Regards
you can add a custom converter implement Converter<String, OrderOptionEnum>
there you implement your own convert logic from string to your enum.
something like this
public class OrderOptionEnumMongoConverter implements Converter<String, OrderOptionEnum> {
@Override
public OrderOptionEnum convert(String source) {
for (OrderOptionEnum OrderOptionEnum : OrderOptionEnum.values()) {
if (OrderOptionEnum.name().equals(source))
return OrderOptionEnum;
}
return null;
}
}
Notice !!! This converter will try to convert each string in mongo to your enum, thus may result in unwanted conversions, so make sure you do this only when needed.
you can add @ReadingConverter
if you want this convert only when reading from mongo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With