在未来的失败中传播信息

问题描述

我正在使用可完成的期货来做一堆ngOnInit(): void { this._dataService.currentUserId.subscribe(userId => this.userId = userId); if(this.userId.length === 0){ this.userService.getUserProfile().subscribe( res => { this.userDetails = res['user']; this.userId = this.userDetails._id; this.getProducts(); },err => { console.log(err); } ); } else { this.getProducts(); } }X与互联网对话,可能失败也可能失败。当我调用X时,我给它传递了一个值,我们称它为Xvalue

X(value)

以上是我正在玩的内容的摘要。归结为分析结果集,我可以看到测试中所有失败/未失败的值(即,对或错)。

    private void X(String value) {

        CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(()-> {
            try {
               Object response = talkToExternalThing(value);
            } catch (InterruptedException e) {
                throw new CompletionException(e.getCause());
            }
            return true;
        }).exceptionally(ex -> false);
        futures.add(future);
    }

我的问题是,我不仅想知道它是否失败,还想要其他元数据,例如导致失败的Map<Boolean,List<CompletableFuture<Boolean>>> result = futures.stream() .collect(Collectors.partitioningBy(CompletableFuture::isCompletedExceptionally)); 。我希望可能有一个异常对象,因此我可以对其进行分析。值得注意的是,异常value

解决方法

这是我的建议:

ExecutorService executorService = Executors.newCachedThreadPool();

private void X(String value) {
    CompletableFuture<Pair<Boolean,String>> future = new CompletableFuture<>();
    executorService.execute(() -> {
        try {
            Object response = talkToExternalThing(value);
        } catch (InterruptedException e) {
            // un-successfully,with the value
            future.complete(new Pair<>(false,value));
            return;
        }

        // successfully,with the value
        future.complete(new Pair<>(true,value));
    });
    
    futures.add(future);
    
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...