Error codes with variable String descriptions in Java
I would like to have error codes in my Java project, but they should have variable String descriptions. For example, I might have two 开发者_如何学PythonBadCharacterCount errors, but I'd like to represent them as two different strings, e.g. "Bad character count: expected 50, got 60" and "Bad character count: expected 40, got 70." I'd like to be able to recognize both of these cases as BadCharacterCount errors, and ideally have these in an enum of some sort.
There's a nice discussion of a similar problem here: Best way to define error codes/strings in Java?
However, they don't deal with the case of variable error Strings... Any ideas?
I think your two error descriptions:
Bad character count: expected 50, got 60
And:
Bad character count: expected 40, got 70.
Are already the same. The string is:
Bad character count: expected %s, got %s.
Then when you need to construct the error message, just make sure to pass it through String.format
:
String.Format(Error.BadCharacterCount, 50, 60)
And
String.Format(Error.BadCharacterCount, 40, 70)
Consider using the error string as a format for String.format(). Of course, you then have to be careful to have your arguments for each error line up correctly with the particular format.
You could have something like this:
public class BadCharacterCountException extends Exception {
public BadCharacterCountException(int expected, int recieved) {
super("Bad character count: expected " + expected + ", got " + recieved + ".");
}
}
or
public enum ErrorCode {
BadCharacterCount("Bad character count: expected {0}, got {1}.");
private final String message;
private ErrorCode(String message){
this.message = message;
}
public String getErrorMessage(Object... args) {
return MessageFormat.format(message, args);
}
}
精彩评论