首页 > 解决方案 > Mono.subscribe() 向客户端抛出异常

问题描述

我试图找出为什么运行时异常没有传播回客户端。我有下一段代码,所以当我返回 Mono.error 时,应该在订阅错误部分进行处理,以便向客户端抛出异常,但这并没有发生。知道我做错了吗?

    public void onmethod(EventDetails eventDetails, String eventType) {
        messageConverter.convertAndSendMessage(eventType, eventDetails)
                .flatMap(aBoolean -> {
                    if (aBoolean)
                        log.debug("Event published");
                    else {
                        log.debug("Problem publishing event.");
                        return Mono.error(new RuntimeException("Problem publishing event."));
                    }
                    return Mono.just(true);
                })
                .doOnError(throwable -> log.error("Failed to consume message", throwable))
                .subscribe(
                        next -> { } ,
                        error -> {
                            throw Exceptions.propagate(error);
                        }
                );
}

这是我必须验证方法行为的测试。由于抛出任何异常,此测试失败。但是,我可以在日志中看到发生了异常。

        Assertions.assertThrows(RuntimeException.class, () ->
                consentsListener.onmethod(
                        eventDetails, "eventType")
        );
19:44:32.463 [main] ERROR events.auth.ConsentsListenerImpl - Failed to consume message
java.lang.RuntimeException: Problem publishing event. 
    at events.auth.ConsentsListenerImpl.lambda$publishMessage$0(ConsentsListenerImpl.java:121)
    at reactor.core.publisher.FluxFlatMap.trySubscribeScalarMap(FluxFlatMap.java:152)
    at reactor.core.publisher.MonoFlatMap.subscribeOrReturn(MonoFlatMap.java:53)
    at reactor.core.publisher.Mono.subscribe(Mono.java:4084)
    at reactor.core.publisher.Mono.subscribeWith(Mono.java:4214)
    at reactor.core.publisher.Mono.subscribe(Mono.java:4070)
    at reactor.core.publisher.Mono.subscribe(Mono.java:4006)
    at reactor.core.publisher.Mono.subscribe(Mono.java:3978)
    at ...

org.opentest4j.AssertionFailedError: Expected java.lang.RuntimeException to be thrown, but nothing was thrown.

非常感谢您提前。此致。

标签: javaspring-bootspring-webfluxsubscribe

解决方案


我试图找出为什么运行时异常没有传播回客户端。

因为您正在订阅它,这几乎可以肯定是错误的做法。框架(在这种情况下为 Webflux)应该是控制对您的发布者的订阅。

如果您删除subscribe()该链上的调用,将您的方法更改为返回Mono<Boolean>,然后在该方法中返回整个链,它应该按预期工作。


推荐阅读