【问题标题】:Convince me I'm wrong about using exceptions for user validation说服我使用异常进行用户验证我错了
【发布时间】:2011-09-01 20:38:12
【问题描述】:

虽然many people say you should not use exceptions to handle bad user input,但很难找到共识。不过,我不相信在我的具体情况下这样做是坏事。你能解释一下我为什么错了吗?

我的代码(请只关注异常处理方面)如下。我在这里使用异常的理由是,如果我不这样做,假设我想让验证逻辑接近关键字解析(因为解析和验证是紧密耦合的),我将不得不更改三个方法(submitOnAdd、submitOnUpdate、 getKeywords) 让他们处理这种特殊情况。您认为我在这种情况下使用异常肯定是错误的,还是个人风格问题?

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;
}

【问题讨论】:

    标签: java exception


    【解决方案1】:

    我不能说我永远不会建议在输入验证的某个地方使用异常。但在这种情况下,我会说它增加了很多混乱。我会:

    • 添加一个单独的方法来处理验证。 (可能必须在多个地方调用此方法,这是否定的,但它可能使代码更易于理解)。
    • 在更理想的情况下,我会更接近用户输入进行验证,并且不允许提交无效数据。 (一个可能的负面因素是验证和解析逻辑的分离,但如果你能以某种方式使用同一个类来执行这两种操作,则可以避免这种情况)。

    【讨论】:

    • 其实我们有一个单独的用户验证方法,但是我选择不放我的验证代码的原因是因为它自己验证每个表达式更方便,并且只完成表达式的拆分在解析代码中。我喜欢接近解析的验证,因为在这种情况下它实际上是同一件事。我可以使用同一个类,但它仍然比内联更复杂。我实际上想将 try...catch 逻辑带到基类中,从而保持主要的 internalSubmit() 方法原始。
    • @ripper,这是我之前面临的艰难决定。我的回答表明了我的偏好,但我认为我不会重构现有代码,因此我不会对其他开发人员做出不同的偏好有太大问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 2014-12-13
    相关资源
    最近更新 更多