Spring Reactive Development - Error Handling

Reactive Developments 对于异常处理, 主要有3个方法, one rrorContinue, one rrorReturn and one rrorResume.

下面我们用代码体验一下他们之间的区别

   private Mono<String> getEmployeeName(String id) {
        Map<String, String> employees = new HashMap<>();
        employees.put("1", "aSha");
        employees.put("2", "billy");
        employees.put("3", "cindy");
        employees.put("4", "davide");
        employees.put("5", "ella");
        employees.put("6", "flee");
        employees.put("7", "galosh");
        employees.put("8", "hank");

        String name = employees.get(id);
        try {
//            Thread.sleep(new Random().nextInt(100)*100);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException("Thread sleep Error!!!");
        }
        if("ella".equals(name)){
            throw new RuntimeException("Not Found!!!");

        }
        if (StringUtils.isBlank(name)) {
            throw new RuntimeException("Not Found!!!");
        }
        return Mono.just(name);
    }

  


@Test public void testFlatMapSequentialParallelScheduler() { List<String> employeeIds = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8"); Flux<String> nameFlux = Flux.fromIterable(employeeIds) .window(2) .flatMapSequential(identities -> identities.flatMap(this::getEmployeeName).subscribeOn(parallel())) .onErrorContinue((e,i)->log.info("error is ",e)) // .onErrorResume(e -> { // log.info("inside error resume!",e); // return Mono.just("Default"); // } // ) // .onErrorReturn("default") .log(); StepVerifier.create(nameFlux) .expectNextCount(8) .verifyComplete(); }

  其中 one rrorResume 和 one rrorReturn 处理异常的结果是一样的, 看源码可以发现onErrorReturn 调用onErrorResume,像这种流式计算通常遇到异常会直接返回, 处理到第5个请求直接打印default就返回了。

     而onErrorContinue 会跳过异常直接向后执行,所以最后会打印7条信息。

 

所以如果是一次单独请求,或者遇到异常需要立即返回的情况使用onErrorResume和onErrorReturn, 而如果是流式计算,希望跳过异常元素的,则应该使用onErrorContinue。

     

上一篇:一.webpack默认打包


下一篇:Committee to boost development of Chinese language teachers