When building a system, we often need to define many error classes, including error codes and error messages. In most cases, we use the most traditional way to do it, such as defining a set of error codes first, and then defining a set of error messages. The error messages are placed in the properties file or database, loaded into the memory when the system starts, and placed in the map There is a one-to-one correspondence between the neutral and error codes, and the error information is obtained through the error code and returned to the user during use. Later, custom Annotation appeared in JAVA, which provided us with a more elegant way to manage error message classes. A small DEMO is written below. If you are interested, you can refer to it. JAVA custom Annotation is very useful, especially in the framework development process, and will be recorded slowly in the future.

First define an Annotation for the error code definition class.

package errorAno;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ErrorDefineClass {
    String value() default "error message description";
}

The ElementType.TYPE of the Annotation of this error code definition class means that it can act on the class or interface. You can click to see the details. Various types have different uses.

Define another Annotation for the error code attribute

package errorAno;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ErrorDefinition {
    String value();
}

The ElementType.FIELD of the Annotation of this error code attribute represents that it is an annotation acting on a class attribute.

Then define a loading and parsing class for error code classes, or build a global context for error code management.

package errorAno;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

public class ErrorContext {

    public final static int SUCCESS = 0;

    static private Map<Integer, String> errorMap;

    static {
        errorMap = new HashMap<Integer, String>();
        ErrorContext.errorMap.put(0, "Business successed!");
    }

    /*
     *return the preloaded error message without exception
     */
    public static String errnoExplain(int errno) {
        String explain = errorMap.get(errno);
        String backup = String.valueOf(errno);
        return explain != null ? explain : backup;
    }

    /*
     *return unloaded error message without exception
     */
    public static String errnoExplain(int errno, String explain) {
        if (errorMap.containsKey(errno)) {
            return errorMap.get(errno);
        } else {
            String backup = String.valueOf(errno);
            return explain != null ? explain : backup;
        }
    }

    /*
    * analyzed the error class and load them in to memory
    * */
    protected static void proxyExplain(Class<? extends ErrorContext> define) {
        //make sure the error def class extends ErrorContext
        if (define != null && define != ErrorContext.class) {
            final String dname = define.getName();
            //make sure the error class is Annotated by ErrorDefineClass
            if (define.isAnnotationPresent(ErrorDefineClass.class)) {
                Class<ErrorDefinition> defClazz = ErrorDefinition.class;
                //analyze the error fields
                for (Field field : define.getDeclaredFields()) {
                    //make sure the fields is Annotated by ErrorDefinition
                    if (field.isAnnotationPresent(defClazz)) {
                        //make sure the fields is modified by public
                        if (Modifier.isPublic(field.getModifiers())) {
                            try {
                                ErrorDefinition entry = null;
                                int errno = field.getInt(null);
                                entry = field.getAnnotation(defClazz);
                                ErrorContext.errorMap.put(errno, entry.value());
                                System.out.println("analyzed error message successed:" + entry.value());
                            } catch (Exception e) {
                                System.out.println("analyze error message exception");
                            }
                        }
                    }
                }
            }
        }
    }
}

For details, please refer to the comments in the code. Its main function is to load all error code definition classes and attributes when the system starts, and then you can directly call to find the corresponding error code when using it.

Finally, let’s see how to integrate it into your system

package errorAno;

@ErrorDefineClass
public class BusinessError extends ErrorContext{

    /*
    * preload this error Class when system is startup
    * */
    static {
        ErrorContext.proxyExplain(BusinessError.class);
    }

    @ErrorDefinition("The action code is incorrect")
    final public static int ERR_ACTION_CODE = 1;

    @ErrorDefinition("The parameters is incorrect")
    final public static int ERR_PARAMETER = 2;


    public static void main(String[] args) {
        System.out.println(ErrorContext.SUCCESS);
        System.out.println(ErrorContext.errnoExplain(1));
        System.out.println(ErrorContext.errnoExplain(2));
    }
}

This is an error code class that you need to define in the system. This class will be automatically loaded when the system starts. This kind of Annotation usage does not require the previous operations of cyclically loading maps or various data structures. Write according to the Annotation standard, and the system will automatically load the content you need. Let’s see the test results

The management of error codes can be in the database or in properties. There is no difference between good and bad. It just makes different choices according to different systems and usage scenarios. Define the use of Annotation for your reference.


发表回复

Thanks for your support to bet365fans!