Best way to define error codes/strings in Java?

前端 未结 13 768
别那么骄傲
别那么骄傲 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:24

    At my last job I went a little deeper in the enum version:

    public enum Messages {
        @Error
        @Text("You can''t put a {0} in a {1}")
        XYZ00001_CONTAINMENT_NOT_ALLOWED,
        ...
    }
    

    @Error, @Info, @Warning are retained in the class file and are available at runtime. (We had a couple of other annotations to help describe message delivery as well)

    @Text is a compile-time annotation.

    I wrote an annotation processor for this that did the following:

    • Verify that there are no duplicate message numbers (the part before the first underscore)
    • Syntax-check the message text
    • Generate a messages.properties file that contains the text, keyed by the enum value.

    I wrote a few utility routines that helped log errors, wrap them as exceptions (if desired) and so forth.

    I'm trying to get them to let me open-source it... -- Scott

提交回复
热议问题