我了一系列異常的消息:處理可變字符串格式的通用方法?
enum myEnum {
BASIC(1, "An error occurred"),
WITH_ERRORID(2, "Error id: {0}"),
DETAILED(3, "Problem in record {0} with index {1}");
};
我也是有記錄單,可重複使用的權威和拋出一個自定義異常:
public void throwException (myEnum message) {
log.addEntry(message);
throw new CustomException(message);
}
調用該方法是直截了當:
throwException (myEnum.DETAILED);
我現在正在用最優雅的方式格式化字符串。我可以一個toString()方法添加到枚舉基於輸入數量來格式化字符串,並更改throwException接受一個字符串代替:
String msg = message.toString(variable);
throwException (msg);
String msg2 = message.toString(variable, otherVariable);
throwException (msg2);
String msg3 = message.toString(variable, otherVariable, nextVariable);
throwException (msg3);
雖然這工作,我想移動的在throwException()中重複toString調用。我正在考慮傳遞一個ArrayList throwException()。但是,我還要把這些檢查列表的大小之前,我格式化字符串:
if (list.size == 1) MessageFormat.format(message, list.get(0));
if (list.size == 2) MessageFormat.format(message, list.get(0), list.get(1));
是解決這個問題的一個更好的技術或者設計方法?