|
| 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