Skip to content

Commit b83dc9d

Browse files
committed
✨ throwableFunction
1 parent 65e3b9d commit b83dc9d

File tree

2 files changed

+52
-2
lines changed

2 files changed

+52
-2
lines changed

summer-java-core/src/main/java/com/dianpoint/summer/lang/ThrowableConsumer.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ default void handleException(T t, Throwable throwable) {
2626
* @param t 入参
2727
*/
2828
default void execute(T t) {
29-
29+
execute(t, this::handleException);
3030
}
3131

3232
default void execute(T t, BiConsumer<T, Throwable> exceptionHandler) throws NullPointerException {
@@ -45,6 +45,6 @@ default void execute(T t, ThrowableConsumer<T> consumer) throws NullPointerExcep
4545
default void execute(T t, ThrowableConsumer<T> consumer, BiConsumer<T, Throwable> exceptionHandler)
4646
throws NullPointerException {
4747
AssertUtils.assertNotNull(exceptionHandler, () -> "The 'exceptionHandler' must not be null");
48-
consumer.execute(t,exceptionHandler);
48+
consumer.execute(t, exceptionHandler);
4949
}
5050
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.dianpoint.summer.lang;
2+
3+
import com.dianpoint.summer.utils.AssertUtils;
4+
5+
import java.util.function.BiFunction;
6+
7+
/**
8+
* 一个通用的抽象的处理异常的function
9+
*
10+
* @param <T> 入参
11+
* @param <R> 结果
12+
*/
13+
@FunctionalInterface
14+
public interface ThrowableFunction<T, R> {
15+
16+
R apply(T t) throws Throwable;
17+
18+
default R handlerException(T t, Throwable throwable) {
19+
throw new RuntimeException(throwable);
20+
}
21+
22+
default R execute(T t, BiFunction<T, Throwable, R> exceptionHandler) {
23+
R result;
24+
try {
25+
result = apply(t);
26+
} catch (Throwable failure) {
27+
result = exceptionHandler.apply(t, failure);
28+
}
29+
return result;
30+
}
31+
32+
default R execute(T t) throws RuntimeException {
33+
return execute(t, this::handlerException);
34+
}
35+
36+
default <T, R> R execute(T t, ThrowableFunction<T, R> function, BiFunction<T, Throwable, R> exceptionHandler)
37+
throws IllegalArgumentException {
38+
AssertUtils.assertNotNull(function, "The 'function' must not be null");
39+
AssertUtils.assertNotNull(exceptionHandler, "The 'exceptionHandler' must not be null");
40+
41+
return function.execute(t, exceptionHandler);
42+
}
43+
44+
default <T, R> R execute(T t, ThrowableFunction<T, R> function) throws IllegalArgumentException {
45+
AssertUtils.assertNotNull(function, "The 'function' must not be null");
46+
return execute(t, function, function::handlerException);
47+
}
48+
49+
50+
}

0 commit comments

Comments
 (0)