【问题标题】:Using enumeration to represent error messages legibily - is it good practice?使用枚举清晰地表示错误消息 - 这是一种好习惯吗?
【发布时间】:2013-04-07 05:52:34
【问题描述】:

我想将我的错误消息和内容合并到一个文件中,并尽可能使我的代码更具可读性。

这是我的枚举文件中的一个示例:

public enum ZipErrorType {

// START: define exception messages (alphabetical order)
EMPTY_FILE_NAME_IN_LIST {
    public String toString() {
        return "One or more null/empty filename(s) found";
    }
},

FILE_DOESNT_EXIST {
    public String who(String sThisFile) {
        return "[" + sThisFile + "] does not exist";
    }
},

FILE_LIST_IS_NULL {
    public String toString() {
        return "File list is null/empty";
    }
},

FILENAME_NOT_ABSOLUTE {
    public String who(String sThisFile) {
        return "[" + sThisFile + "] is not absolute";
    }
},

MUST_BE_DIR {
    public String who(String sThisFile) {
        return "[" + sThisFile + "] must be a directory";
    }
},

MUST_BE_FILE {
    public String who(String sThisFile) {
        return "[" + sThisFile + "] must be a file";
    }
},

NULL_OR_EMPTY {
    public String who(String sThisFile) {
        return "[" + sThisFile + "] is null/empty";
    }
},

OUTPUT_FILE_ALREADY_EXISTS {
    public String who(String sThisFile) {
        return "[" + sThisFile + "] already exists";
    }
},

OUTPUT_FILENAME_EMPTY {
    public String toString() {
        return "Output filename is null/empty";
    }
},

OUTPUT_PATH_EMPTY {
    public String toString() {
        return "Output path is null/empty";
    }
},
// END: define exception messages

NONE {};

public String who(String sThisFile) { return ""; }
}

然后在我的程序中,我的代码如下:

private static ZipErrorType getFileErrorsIfAny(String sFilename, boolean shouldBeFile) {

    // check if given filename is absolute
    File file = new File(sFilename);
    if (!file.isAbsolute()) {
        return ZipErrorType.FILENAME_NOT_ABSOLUTE;
    }

    // check if file exists
    if (!file.exists()) {
        return ZipErrorType.FILE_DOESNT_EXIST;
    }

    // check if corresponding file is a file when it shouldn't be...
    if (file.isFile() && !shouldBeFile) {
        return ZipErrorType.MUST_BE_DIR;
    }
    // ...or a directory when it should be a file
    else if (file.isDirectory() && shouldBeFile) {
        return ZipErrorType.MUST_BE_FILE;
    }

    return ZipErrorType.NONE;
}

...以及我如何使用枚举的示例:

    // check input files
    for (String sFile : files) {
        if (sFile == null || sFile.trim().length() == 0) {
            throw new NullPointerException("One or more filename is null/empty");
        }

        errorIfAny = getFileErrorsIfAny(sFile.trim(), true); 
        if (!errorIfAny.equals(ZipErrorType.NONE)) {
            throw new ZipInputException(errorIfAny.who(sFile.trim()));
        }
    }

现在我知道仅凭这些代码 sn-ps 很难判断,但是从一般的角度来看,这样可以吗?我正在做的事情不值得麻烦吗?有没有办法改善这一点?

【问题讨论】:

  • 考虑将此问题发布到codereview.stackexchange.com。看来您没有任何问题或疑问,只是需要同行评审。
  • 我不确定它是否更好,但在我当前的项目中,我们以相同的方式使用枚举......但每个返回的字符串只是用于 i18n 的标识符

标签: java exception-handling error-handling enums


【解决方案1】:

这似乎有可能导致代码周围出现许多大量的enums。

这不是第一次有人想将日志消息与日志语句分开。

事实上java.util.logging 已经有一个为本地化设计的framework for this

它使用包含消息的.properties 文件。
您会在类路径中获得带有文件路径的记录器:-

Logger logger = Logger.getLogger("com.example", "path/to/messages.properties");

然后使用属性键完成记录语句

logger.log(level, "messageKey");

您可以参数化日志记录,因为它使用MessageFormat 语法

zip.fileDoesNotExist={0} does not exist

logger.log(level, "zip.fileDoesNotExist", file);

这些参数非常灵活,您可以在其中指定格式信息,甚至在需要时使用ChoiceFormat

所有这些的主要优点是您的消息位于单独的文件中,而不是class并且您可以使用logging.properties 文件随意打开和关闭登录。您甚至可以为单个课程打开和关闭登录。 并且您可以登录到多个文件、控制台、发送有关错误的电子邮件等

所以,总而言之。使用现有的日志框架。不要自己动手。

免责声明:我只谈论 JUL,因为 JUL 是内置于 Java 中的 - 您不需要任何 3rd 方库,那里有很多很多其他框架。

【讨论】:

    【解决方案2】:

    我建议使用简单的字符串模板而不是枚举来构建错误消息。 像这样的:

    String EMPTY_FILE_NAME_IN_LIST_TEMPLATE = "One or more null/empty filename(s) found";
    String FILE_DOESNT_EXIST_TEMPLATE = "[ %s ] does not exist";
    String FILE_LIST_IS_NULL_TEMPLATE = "File list is null/empty";
    String FILENAME_NOT_ABSOLUTE_TEMPLATE = "[ %s ] is not absolute";
    String MUST_BE_DIR_TEMPLATE = "[ %s ] must be a directory";
    String MUST_BE_FILE_TEMPLATE = "[ %s ] must be a file";
    String NULL_OR_EMPTY_TEMPLATE = "[ %s ] is null/empty";
    String OUTPUT_FILE_ALREADY_EXISTS_TEMPLATE = "[ %s ] already exists";
    String OUTPUT_FILENAME_EMPTY_TEMPLATE = "Output filename is null/empty";
    String OUTPUT_PATH_EMPTY_TEMPLATE = "Output path is null/empty";
    

    然后,使用String.format(template, sFilename) 构建实际消息。

    您也可以考虑直接从getFileErrorsIfAny() 方法中抛出异常:

    File file = new File(sFilename);
    if (!file.isAbsolute()) {
        throw new ZipInputException(String.format(FILENAME_NOT_ABSOLUTE_TEMPLATE, sFilename));
    }
    

    对我来说看起来更干净、更紧凑。

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 2013-08-03
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      • 2019-03-06
      • 2013-03-30
      • 2015-09-02
      相关资源
      最近更新 更多