静音模式【其他模式】

静音模式

public class Mute {
    /**
     * Mute Pattern【静音模式】:
     * 提供一个模板来抑制任何声明但不能发生或只能被记录的异常,当在执行某些业务逻辑时,
     * 该模板消除了编写重复的 try-catch 块的需要。
     */
    @Test
    public void all() {
        MuteExecutor.syncExecute(() -> {
            throw new RuntimeException("muted");
        });
    }
}

interface Action {
    void execute();
}

@Slf4j
final class MuteExecutor {
    public static void syncExecute(Action action) {
        try {
            action.execute();
        } catch (final Exception e) {
            log.error("静默处理异常", e);
        }
    }

    public static void asyncExecute(Action action) {
        try {
            CompletableFuture.runAsync(action::execute);
        } catch (final Exception e) {
            log.error("静默处理异常", e);
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/zhuxudong/p/10211097.html
今日推荐