【发布时间】: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;
}
【问题讨论】: