不喜欢写try-catch语句的看过来
/**
* 异常捕获
* @author Cpz
* @since 2022-07-30
*/
@Slf4j
public final class TryCatchHandler<T, R> {
private T param;
private R result;
private TryCatchHandler(T param) {
this.param = param;
}
private TryCatchHandler(T param, R result) {
this.param = param;
this.result = result;
}
/**
* 初始化参数信息,没有默认值抛出异常将返回null,注意NPE处理
*
* @param param
* @param <T>
* @param <R>
* @return
*/
public static <T, R> TryCatchHandler<T, R> of(T param) {
return of(param, null);
}
/**
* 使用默认值,抛出异常将会使用该默认值返回
*
* @param param 参数
* @param defaultVal 抛异常时默认值
* @param <T>
* @param <R>
* @return
*/
public static <T, R> TryCatchHandler<T, R> of(T param, R defaultVal) {
return new TryCatchHandler<>(param, defaultVal);
}
/**
* 异常逻辑处理
*
* @param function
* @return
*/
public R apply(ExceptionFunction<T, R> function) {
try {
result = function.apply(param);
} catch (Throwable e) {
log.error(e.getMessage(), e);
}
return result;
}
/**
* @author Cpz
* @Date: 2022-07-29
*/
@FunctionalInterface
public interface ExceptionFunction<T, R> {
R apply(T t) throws Throwable;
}
/**
* 测试方法,用于测试用例
* @param isThrow
* @return
* @throws Exception
*/
private static int test(boolean isThrow) throws Exception {
if (isThrow) {
throw new RuntimeException("测试抛异常");
}
return 2;
}
public static void main(String[] args) {
Integer apply1 = TryCatchHandler.of(true, 100).apply(TryCatchHandler::test);
Integer apply2 = TryCatchHandler.<Boolean, Integer>of(false).apply(TryCatchHandler::test);
System.out.println(apply1 + ":" + apply2);
}
}
网友评论