投掷和记录例外,这是一种更好的方法

Jam*_*sev 7 java error-handling

最终,我想

if (badThingsHappen) {
 log the issue
 throw exception with description
}
Run Code Online (Sandbox Code Playgroud)

这里明显的冗余是通常异常描述和要记录的消息(通常)是相同的.

这看起来不必要地冗长

if (badThingsHappen) {
 logger.error("oh no! not again!");
 throw new AppException("oh no! not again!");
}
Run Code Online (Sandbox Code Playgroud)

声明临时字符串感觉不对

if (badThingsHappen) {
 String m = "oh no! not again!";
 logger.error(m);
 throw new AppException(m);
}
Run Code Online (Sandbox Code Playgroud)

是否可以让Exception的构造函数处理日志记录?有更好的(更干净的)方式吗?

Tho*_*ler 3

您可以使用实用方法:

public class AppException extends Exception {
    public static AppException logAndThrow(Logger logger, String message) throws AppException {
        AppException e = new AppException(message);
        // log the stack trace as well
        logger.error(message, e);
        throw e;
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用它:

if (badThingsHappen) {
    AppException.logAndThrow(logger, "oh no! not again!");
}
Run Code Online (Sandbox Code Playgroud)