0

I would like to have error codes in my Java project, but they should have variable String descriptions. For example, I might have two BadCharacterCount 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?

Community
  • 1
  • 1
Vinay
  • 61
  • 7

3 Answers3

0

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.

Ed Staub
  • 15,480
  • 3
  • 61
  • 91
0

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)
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
0

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);
    }
}
Jeffrey
  • 44,417
  • 8
  • 90
  • 141