Convince me that I am mistaken in using exceptions to validate users

It is difficult to find consensus, although many say that you should not use exceptions to handle incorrect user input . However, I am not sure if this is bad in my particular case. Could you explain why I am wrong?

My code (please focus only on the aspect of exception handling). My rational use of exceptions here is that if I hadn’t done this, assuming that I want the validation logic to be close to parsing keywords (since parsing and validation are closely related), I would have to change three methods (submitOnAdd , submitOnUpdate, getKeywords) to get them to handle this exception. Do you think I'm definitely wrong in this case to use exceptions, or is it a personal style issue?

public SubmitResponse internalSubmit(Map<String, String[]> submitParameters) {
  try {
      if (!submitParameters.containsKey("foo")) {
        return submitOnAdd(submitParameters);
      } else {
        return submitOnModify(submitParameters);
      }
  } catch (SubmitErrorException e) {
      return SubmitResponse.fieldError(Arrays.asList(e.getSubmitError()));
  }
}

SubmitResponse submitOnAdd(Map<String, String[]> submitParamters) {
  // do some stuff
  // ...
  if (addKeywordList(createKeywordList(submitParameters.get("concatenated_keywords"))
    return SubmitResponse.OK();
  return SubmitResponse.bad("Failed to add");
}

SubmitResponse submitOnUpdate(Map<String, String[]> submitParamters) {
  // do some other stuff
  // ...
  if (updateKeywordList(createKeywordList(submitParameters.get("concatenated_keywords"))
    return SubmitResponse.OK();
  return SubmitResponse.bad("Failed to update");
}

List<Keyword> getKeywords(String concatenatedKeywords) {
  List<String> rawKeywords = splitKeywords(concatenatedKeywords);
  return Collections.transform(new Function<String, Keyword>() {
      @Override
      public KeywordListProto.Keyword apply(String expression) {
        return buildKeyword(expression);
      }
    });
}

private Keyword buildKeyword(String rawKeyword) {
  // parse the raw keyword
  if (/*parsing failed */)
    throw new SubmitResponseException("Failed to parse keyword " + rawKeyword);

  return parsedKeyword;
}
+3
source share
1 answer

I cannot say that I would never advise using Exceptions somewhere in input validation. But in this case, I would say that this adds a lot of confusion. I would either:

  • . (, , , ).
  • . ( , - , ).
+1

All Articles