代码之家  ›  专栏  ›  技术社区  ›  petehallw

处理反应流中的异常并返回上一次调用的值

  •  0
  • petehallw  · 技术社区  · 5 年前

    我在反应流方面遇到了一些问题,根据下面的代码,函数的返回值应该是调用 myServiceConnector.createSummary(request) ,无论以下调用是否 otherService.postDetails(summary, details, item) 是否引发异常。如果它抛出异常,我只想做一些日志记录,否则就忽略它。

    public Mono<Summary> createSummary(final Details details, String authorisation)
    {
        return myService.doSomething(details.getItemId(), authorisation)
                           .zipWhen(item -> Mono.just(convertToMyRequest(item, details, myServiceConfig.getBaseRedirectUrl())))
                           .flatMap(tuple -> {
                               MyItem item = tuple.getT1();
                               OrderRequest request = tuple.getT2();
                               return myServiceConnector.createSummary(request)
                                                           .doOnSuccess(summary -> otherService.postDetails(summary, details, item)
                                                                                                                .onErrorContinue((o,i) -> {
                                                                                                                    // Log error
                                                                                                                }));
    
                           });
    }
    

    目前看来 onErrorContinue call未被调用(我正在强制 其他服务。postDetails(摘要、详细信息、项目) 在我的测试中)。我也试过了 onErrorResume 虽然调用了,但仍然抛出了异常,所以我没有得到 Summary 返回的对象。不确定我的错误处理是否正确。

    更新以包含以下测试代码:

    @Test
    public void returnSummaryWhenOtherServiceFails()
    {
        Details details = Details.builder()
                                 .itemId(ITEM_ID)
                                 .build();
    
        when(myServiceConfig.getBaseRedirectUrl()).thenReturn(BASE_REDIRECT_URL);
        when(myService.doSomething(ITEM_ID, AUTH_STRING)).thenReturn(Mono.just(ITEM));
        when(myServiceConnector.createSummary(any())).thenReturn(SUMMARY);
        when(otherService.postDetails(any(), any(), any())).thenThrow(WebClientResponseException.class);
    
        summaryService.createSummary(details, AUTH_STRING).block();
        
        verify(myServiceConnector).createSummary(any());
    }
    

    由于以下原因,测试失败:

    org.springframework.web.reactive.function.client.WebClientResponseException

    0 回复  |  直到 5 年前
        1
  •  0
  •   Max Grigoriev    5 年前

    如果你想打电话 otherService.postDetails 在后台,不在乎结果,然后你可以这样做:

    otherService.postDetails(...).subscribe() 
    

    otherService.postDetails(...).publishOn(Schedulers.elastic()).subscribe()
    

    这取决于你的代码。

    或者,您可以这样更改代码:

    myServiceConnector.createSummary(request)
    .flatMap(summary -> otherService.postDetails(summary, details, item)
        .onErrorContinue(...)
    )
    

    它将运行 createSummary 然后 postDetails 如果 postDetails 那就失败了 onErrorContinue 将被触发。