Best way to define error codes/strings in Java?

前端 未结 13 799
别那么骄傲
别那么骄傲 2020-12-12 08:37

I am writing a web service in Java, and I am trying to figure out the best way to define error codes and their associated error strings. I need to have a nu

13条回答
  •  忘掉有多难
    2020-12-12 09:23

    Overloading toString() seems a bit icky -- that seems a bit of a stretch of toString()'s normal use.

    What about:

    public enum Errors {
      DATABASE(1, "A database error has occured."),
      DUPLICATE_USER(5007, "This user already exists.");
      //... add more cases here ...
    
      private final int id;
      private final String message;
    
      Errors(int id, String message) {
         this.id = id;
         this.message = message;
      }
    
      public int getId() { return id; }
      public String getMessage() { return message; }
    }
    

    seems a lot cleaner to me... and less verbose.

提交回复
热议问题