Skip to content

Instantly share code, notes, and snippets.

@friddle
Created July 11, 2022 01:36
Show Gist options
  • Save friddle/5b2d5782d5d340403aa100667f59bcdd to your computer and use it in GitHub Desktop.
Save friddle/5b2d5782d5d340403aa100667f59bcdd to your computer and use it in GitHub Desktop.
BizLambdaUtil 常用的一些lambda工具函数类
@Slf4j
public class BizLambdaUtil {
public static<R> R alsoIf(R obj,boolean isIf,Consumer<R> consumer){
try {
if(isIf){
consumer.accept(obj);
}
return obj;
} catch (Exception e) {
log.error("try method failed", e);
return obj;
}
}
public static<R> R also(R obj, Consumer<R> consumer){
return alsoIf(obj,true,consumer);
}
public static<R> R invoke(Supplier<R> function, R defaultValue){
try {
R result=function.get();
if(result==null){
return defaultValue;
}
return result;
} catch (Exception e) {
log.debug("invoke method failed:",e);
return defaultValue;
}
}
public static<R> Triple<Boolean, BaseCode, R> invokeWithRsp(Supplier<R> supplier){
try{
return Triple.of(true,null,supplier.get());
}catch (BusinessException e){
return Triple.of(false,e.getError(),null);
}
}
public static String invokeS(Supplier<String> function, String defaultValue){
String result=invoke(function,defaultValue);
if(result.isEmpty()){return defaultValue;}
return result;
}
public static<T,R> R ignoreError(Function<T,R> function)
{
return ignoreError(function,null);
}
public static<T,R> R ignoreError(Function<T,R> function, T args)
{
try {
return function.apply(args);
} catch (Exception e) {
log.debug("try method failed", e);
return null;
}
}
//拦截异常并用自定义异常取代
public static<R> R tryMethod(Function<Void,R> function, BaseCode code){
return tryMethod(function,code,null);
}
//拦截异常并用自定义异常取代
public static<T,R> R tryMethod(Function<T,R> function, BaseCode code,T args)
{
try {
return function.apply(args);
} catch (Exception e) {
log.debug("try method failed", e);
throw new BusinessException(code);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment