title: Best way to define error codes/strings in Java?
body: <p>I am writing a web service in Java, and I am <strong>trying to figure out the best way to define error codes and their associated error strings</strong>. I need to have a numerical error code and an error string grouped together. Both the error code and error string will be sent to the client accessing the web service. For example, when a SQLException occurs, I might want to do the following:</p>
  
  <pre><code>// Example: errorCode = 1, 
  //          errorString = "There was a problem accessing the database."
  throw new SomeWebServiceException(errorCode, errorString);
  </code></pre>
  
  <p>The client program might be shown the message:</p>
  
  <blockquote>
    <p>"Error #1 has occured: There was a
    problem accessing the database."</p>
  </blockquote>
  
  <p>My first thought was to used an <code>Enum</code> of the error codes and override the <code>toString</code> methods to return the error strings. Here is what I came up with:</p>
  
  <pre><code>public enum Errors {
    DATABASE {
      @Override
      public String toString() {
        return "A database error has occured.";
      }
    },
  
    DUPLICATE_USER {
      @Override
      public String toString() {
        return "This user already exists.";
      }
    },
  
    // more errors follow
  }
  </code></pre>
  
  <p><strong>My question is:</strong> Is there a better way to do this? I would prefer an solution in code, rather than reading from an external file. I am using Javadoc for this project, and being able to document the error codes in-line and have them automatically update in the documentation would be helpful.</p>