I am validating some input from a Restlet URL in a utility method (that way if the behavior I take changes, I only change it one place, yay). The legalName essentially validates the value as being alphaNumeric, but I may allow other characters soon.
I try to keep my Exceptions to make sense – what Exception would be the best in this scenario?
public static String getProperty(Request request, String key) {
String value = request.getAttributes().get(key).toString();
// unless something is specifically text, it is a property
if(legalName(value)) return value;
throw new IllegalArgumentException(value);
}
My thoughts are:
- IllegalArgumentException – the key directly leads to an invalid result
- IllegalStateException – we’re trying to use a non-conforming value
- No exception – return an empty string and log the fact that a breach was made
- No exception – remove any undesireable characters, return the sanitized string, and log the fact
Surely I’m not the first person to have to validate input before 🙂
Exceptions like this should be thrown when the property is stored, not retrieved. Check Restlet validation for that.
If you prefer to stick to your solution:
validateName(..)and let it throw the exception. If it doesn’t – return the value.javax.validation.ValidationExceptionlooks the better option, but you can use any of the twoIllegalXExceptionyou mentioned. Just make sure they have a more detailed message.