Description
I'm seeking clarification and improvement around handling invalid wire values for enums wrapped by WireSafeEnum
, especially for enums with useful fields beyond the name itself.
Request:
Please consider either:
- Un-deprecating
asEnumOrThrow()
, or - Making
getInvalidValueException()
public
So that a standard underlying error message and exception can be relied upon to action on exception cases.
Background:
Many enums have fields and methods encapsulating business logic that is important to access, not just the enum constant names. Consider this more concrete example, representing statuses in a system with associated severity levels and user-friendly messages:
public enum ProcessStatus {
OK("green", 1, "All systems operational"),
DEGRADED("yellow", 2, "Performance issues detected"),
DOWN("red", 3, "System unavailable");
private final String colorCode;
private final int severity;
private final String userMessage;
ProcessStatus(String colorCode, int severity, String userMessage) {
this.colorCode = colorCode;
this.severity = severity;
this.userMessage = userMessage;
}
public int getSeverity() {
return severity;
}
public String getColorCode() {
return colorCode;
}
public String getUserMessage() {
return userMessage;
}
// Pattern useful before deprecation:
public static String statusMessageForWireEnum(WireSafeEnum<ProcessStatus> wrappedStatus) {
try {
return wrappedStatus.asEnumOrThrow().getUserMessage();
} catch (IllegalStateException e) {
// Log/report invalid value, provide fallback
}
return DOWN.userMessage;
}
}
Problem:
Previously, asEnumOrThrow()
enabled:
- Accessing enum fields like
userMessage
orseverity
- Explicit handling of invalid wire values by catching exceptions or logging
Since asEnumOrThrow()
is deprecated, it is unclear how to cleanly accomplish this pattern. Methods like asEnum()
and isEmpty()
do not easily allow safe field access nor do they provide a tailored exception for advanced use-cases or error reporting.
Suggestion:
-
Un-deprecate
asEnumOrThrow()
This method enables library users to:- Attempt to access enriched enum fields/methods
- Handle invalid values directly where business context is known
-
Alternatively, make
getInvalidValueException()
public
This would allow the following explicit handling pattern:
if (wrappedStatus.isEmpty()) {
IllegalStateException e = wrappedStatus.getInvalidValueException();
// Log/report invalid value, provide fallback
return DOWN.userMessage;
}
return wrappedStatus.asEnum().getUserMessage();
While slightly less ergonomic than try/catch, it would still provide a recognizable contextual error information. This is much more preferred to forcing all implementors to write their own underlying messages in the case where the json value is not valid. Much better to be able to wrap that standard exception with additional context.
Thank you for your consideration.