opt add ifFail fn

This commit is contained in:
kongweiguang 2023-08-15 18:12:42 +08:00
parent 1f66719187
commit 5f11f26a15
2 changed files with 69 additions and 11 deletions

View File

@ -13,6 +13,7 @@ package org.dromara.hutool.core.lang;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.func.SerSupplier;
import org.dromara.hutool.core.stream.EasyStream;
import org.dromara.hutool.core.text.StrUtil;
import java.util.Collection;
@ -189,6 +190,52 @@ public class Opt<T> {
return null != this.throwable;
}
/**
* 如果包裹内容失败了就执行传入的操作({@link Consumer#accept})
*
* <p> 例如如果值存在就打印结果
* <pre>{@code
* Opt.ofTry(() -> 1 / 0).ifFail(Console::log);
* }</pre>
*
* @param action 你想要执行的操作
* @return this
* @throws NullPointerException 如果包裹里的值存在但你传入的操作为{@code null}时抛出
*/
public Opt<T> ifFail(final Consumer<? super Throwable> action) {
Objects.requireNonNull(action, "action is null");
if (isFail()) {
action.accept(throwable);
}
return this;
}
/**
* 如果包裹内容失败了就执行传入的操作({@link Consumer#accept})
*
* <p> 例如如果值存在就打印结果
* <pre>{@code
* Opt.ofTry(() -> 1 / 0).ifFail(Console::log, ArithmeticException.class);
* }</pre>
*
* @param action 你想要执行的操作
* @param exs 抛出相应异常执行操作
* @return this
* @throws NullPointerException 如果包裹里的值存在但你传入的操作为{@code null}时抛出
*/
@SafeVarargs
public final Opt<T> ifFail(final Consumer<? super Throwable> action, final Class<? extends Throwable>... exs) {
Objects.requireNonNull(action, "action is null");
if (isFail() && EasyStream.of(exs).anyMatch(e -> e.isAssignableFrom(throwable.getClass()))) {
action.accept(throwable);
}
return this;
}
/**
* 判断包裹里元素的值是否存在存在为 {@code true}否则为{@code false}
*

View File

@ -8,6 +8,7 @@ import lombok.NoArgsConstructor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import javax.management.monitor.MonitorSettingException;
import java.util.*;
import java.util.stream.Stream;
@ -208,4 +209,14 @@ public class OptTest {
private String username;
private String nickname;
}
@Test
void testFail() {
Opt.ofTry(() -> 1 / 0)
.ifFail(Console::log)
.ifFail(Console::log, ArithmeticException.class)
.ifFail(Console::log, NullPointerException.class)
.ifFail(Console::log, NullPointerException.class, MonitorSettingException.class)
;
}
}