How to define error codes and error messages in Java?
In Java, we can use Enum to store the error codes and corresponding error messages. We can always keep this in a config file but keeping it inside Enum is a standard choice.
When we generate documentation of the code, the messages get updates as we change it in the code.
public enum Errors { DATABASE(0, "A database connection error has occurred."), DUPLICATE_USER(1, "This username or email already available in our system."); private final int code; private final String description; private Errors(int code, String description) { this.code = code; this.description = description; } public String getDescription() { return description; } public int getCode() { return code; } @Override public String toString() { return code + ": " + description; } }