1

我有一堆错误代码被服务器返回给我。基于这些错误代码,我需要为每个错误代码编写一些逻辑。我不想在我的函数中放置明显的错误。表示这些错误代码的最佳方式是什么?我现在正在使用枚举,

 private enum LoginErrorCode{

   EMAIL_OR_PASSWORD_INCORRECT("101"),
   EMAIL_INCORRECT("102");

    private final String code;

    LoginErrorCode(String code){
      this.code=code;
    }

    public String getCode(){
      return code;
    }
  }

但是如果我收到一个我不知道的错误代码,我不知道如何处理它。请告诉我。

4

2 回答 2

2

这是使用 Enum 的解决方案,我通常使用它来处理您在场景中解释的错误代码:

import java.util.HashMap;
import java.util.Map;

public class EnumSample {

    public static enum LoginErrorCode {

        EMAIL_OR_PASSWORD_INCORRECT("101"), EMAIL_INCORRECT("102"), UNKNOWN_ERROR_CODE("---");

        private static Map<String, LoginErrorCode> codeToEnumMap;

        private final String code;

        LoginErrorCode(String code) {
            this.code = code;
        }

        public String getCode() {
            return code;
        }


        /**
         * Looks up enum based on code.  If code was not registered as enum, it returns UNKNOWN_ERROR_CODE
         * @param code
         * @return
         */
        public static LoginErrorCode fromCode(String code) {
            // Keep a hashmap of mapping between code and corresponding enum as a cache.  We need to initialize it only once
            if (codeToEnumMap == null) {
                codeToEnumMap = new HashMap<String, EnumSample.LoginErrorCode>();
                for (LoginErrorCode aEnum : LoginErrorCode.values()) {
                    codeToEnumMap.put(aEnum.getCode(), aEnum);
                }
            }

            LoginErrorCode enumForGivenCode = codeToEnumMap.get(code);
            if (enumForGivenCode == null) {
                enumForGivenCode = UNKNOWN_ERROR_CODE;
            }

            return enumForGivenCode;
        }
    }

    public static void main(String[] args) {

        System.out.println( LoginErrorCode.fromCode("101")); //Prints EMAIL_OR_PASSWORD_INCORRECT
        System.out.println( LoginErrorCode.fromCode("102")); //Prints EMAIL_INCORRECT
        System.out.println( LoginErrorCode.fromCode("999")); //Prints UNKWNOWN_ERROR_CODE
    }
}
于 2013-07-02T16:57:11.597 回答
0

an 的要点enum是没有无效值;无效值不存在。不可能有LoginErrorCode.EMAIL_ERROR_DOES_NOT_EXIST值。您不必处理不存在的值。这就是enum最佳表示的原因,因为您有一组已知的值要表示。

编辑

由于您需要将错误代码字符串转换为您的枚举,请在您的枚举值中包含一个Map错误代码Strings

public enum LoginErrorCode
{
    EMAIL_OR_PASSWORD_INCORRECT,
    EMAIL_INCORRECT;

    private static Map<String, LoginErrorCode> map;
    // static initializer
    static {
        map = new HashMap<String, LoginErrorCode>();
        map.put("101", EMAIL_OR_PASSWORD_INCORRECT);
        map.put("102", EMAIL_INCORRECT);
    }
    public static LoginErrorCode fromCode(String code)
    {
        return map.get(code);
    }
}

fromCode方法将返回null无效代码。

于 2013-07-02T16:46:46.433 回答