Java 8 在Java8中使用使用者避免forEach中的try-catch时,forEach中出现错误
我有一个log()方法来避免下面的forEach()中的try-catch语句在其他代码中工作Java 8 在Java8中使用使用者避免forEach中的try-catch时,forEach中出现错误,java-8,Java 8,我有一个log()方法来避免下面的forEach()中的try-catch语句在其他代码中工作 public <T> Consumer<T> log(LogConsumer<T, Throwable> logConsumer) { return i -> { try { logConsumer.accept(i); } catch (Throwable e)
public <T> Consumer<T> log(LogConsumer<T, Throwable> logConsumer)
{
return i -> {
try
{
logConsumer.accept(i);
}
catch (Throwable e)
{
log("e = " + e);
}
};
}
@FunctionalInterface
public interface LogConsumer<T, E extends Throwable> {
void accept(T t) throws E;
}
这是因为无法执行使用lambda表达式引发异常的函数。您必须使用
try-catch
块处理异常。但是,为了使代码看起来更可读,请创建一个函数,该函数将处理异常并返回所需的结果
class Task {
public String runJob(Job job, JobType type)
{
try {
...
return result;
} catch (Exception e) {
log.error(e.getMessage());
}
return null;
}
}
如果您关心结果是什么,那么映射它并过滤函数的结果不为null,否则,忽略它,但观察日志中是否有任何错误
然后按如下所示调用它。
注意:下面两种方法都有效,但第二种方法更可靠,因为当并非所有作业都毫无例外地执行时,您可以处理该场景
execute(){
Map Map=getJobMap();
//第一条路
map.forEach(log((作业,类型)->new Taks().runJob(作业,类型));
//另一种方式
List batchResult=map.entrySet().stream()
.map((作业,类型)->new Task().runJob(jon,类型))
.filter(对象::非空)
.collect(Collectors.toList());
if(batchResult.size()==map.size()){
//一切正常(所有操作产生非空结果
}否则{
//必须研究日志,找出哪里出了问题
}
}
发生这种情况是因为您无法执行使用lambda表达式引发异常的函数。您必须使用try catch
块处理异常。但是,为了使代码看起来更可读,请创建一个函数,该函数将处理异常并返回所需结果
class Task {
public String runJob(Job job, JobType type)
{
try {
...
return result;
} catch (Exception e) {
log.error(e.getMessage());
}
return null;
}
}
如果您关心结果是什么,那么映射它并过滤函数的结果不为null,否则,忽略它,但观察日志中是否有任何错误
然后按如下所示调用它。
注意:下面两种方法都有效,但第二种方法更可靠,因为当并非所有作业都毫无例外地执行时,您可以处理该场景
execute(){
Map Map=getJobMap();
//第一条路
map.forEach(log((作业,类型)->new Taks().runJob(作业,类型));
//另一种方式
List batchResult=map.entrySet().stream()
.map((作业,类型)->new Task().runJob(jon,类型))
.filter(对象::非空)
.collect(Collectors.toList());
if(batchResult.size()==map.size()){
//一切正常(所有操作产生非空结果
}否则{
//必须研究日志,找出哪里出了问题
}
}
我需要使用BiConsumer而不是Consumer,但无论如何都要感谢Ilya Serebryannikov的评论Ilya Serebryannikov需要使用BiConsumer而不是Consumer,但无论如何都要感谢Ilya Serebryannikov的评论
execute() {
Map<Job, JobType> map = getJobMap();
// First way
map.forEach( log((job, type) -> new Taks().runJob(job,type)) );
// Another way
List<Object> batchResult = map.entrySet().stream()
.map((job, type) -> new Task().runJob(jon, type))
.filter(Objects::nonNull)
.collect(Collectors.toList());
if (batchResult.size() == map.size()) {
// everythings is ok (all operations resulted in non-null result
} else {
// Have to study logs and figure out what went wrong
}
}