We have a REST API where clients can supply parameters representing values defined on the server in Java Enums.
So we can provide a descriptive error, we add this
We do all our enums like this when it comes to Rest/Json etc. It has the advantage that the error is human readable and also gives you the accepted value list. We are using a custom method MyEnum.fromString instead of MyEnum.valueOf, hope it helps.
public enum MyEnum {
A, B, C, D;
private static final Map NAME_MAP = Stream.of(values())
.collect(Collectors.toMap(MyEnum::toString, Function.identity()));
public static MyEnum fromString(final String name) {
MyEnum myEnum = NAME_MAP.get(name);
if (null == myEnum) {
throw new IllegalArgumentException(String.format("'%s' has no corresponding value. Accepted values: %s", name, Arrays.asList(values())));
}
return myEnum;
}
}
so for example if you call
MyEnum value = MyEnum.fromString("X");
you'll get an IllegalArgumentException with the following message:
'X' has no corresponding value. Accepted values: [A, B, C, D]
you can change the IllegalArgumentException to a custom one.