【问题标题】:How to throw exception or handle filter condition in webflux?如何在 webflux 中抛出异常或处理过滤条件?
【发布时间】:2021-06-18 15:09:53
【问题描述】:
1 customerRepo.findById(customerId) // finding the Customer
2               .switchIfEmpty(Mono.defer(
                        () -> Mono.error(new RuntimeException("not found")))) // if empty throw error
3               .filter(customer -> StringUtils.isEmpty(customer.getType().equals("Regular"))) // add filter condition

4               .switchIfEmpty(Mono.defer(
                        () -> Mono.error(new RuntimeException("no regualar customer")))) // If empty throw error
                        
5               flatMap....... (logic continues)
  1. 根据来自 DB 的 ID 查找客户。
  2. 如果未找到客户 ID 的客户,则会引发错误。
  3. 检查是否有老客户。
  4. 如果没有固定客户,则使用不同的消息引发异常。
  5. 那么我还有进一步的逻辑要继续。

问题:

  1. 这是完全反应式编写的正确方法吗?
  2. 当我连续点击时,我在第 4 行收到 java.lang.RuntimeException: 错误。 (注意:如果客户不在,我不会收到 RuntimeException 第 2 行)
  3. 在编写逻辑的正确方法方面需要帮助。

【问题讨论】:

    标签: spring-boot mono spring-webflux project-reactor flux


    【解决方案1】:

    这是完全反应式写作的正确方法吗?

    您在那里使用的模式本质上没有错。想到两件事:

    • Mono.defer() 在这里并没有真正添加任何内容 - 您也可以只传递一个标准的 Mono.error() 包含两种情况下的异常。
    • 如果您可以不使用自定义异常,则只需使用 single() 方法,如果没有任何异常,该方法将返回标准 NoSuchElementException

    当我连续点击时,我在第 4 行收到 java.lang.RuntimeException: 错误。 (注意:如果客户不在那里,我不会收到 RuntimeException 第 2 行)

    这一定意味着您在第 3 行中的过滤条件总是过滤掉该值 - 否则您不会抛出运行时异常。

    【讨论】:

    • 当然,但是我想要第 4 行和第 2 行的不同消息,所以我需要使用自定义消息。如果第 4 行条件满足,我会在日志中得到异常跟踪,尽管在第 2 行没有异常跟踪。但功能按预期工作。
    猜你喜欢
    • 2015-12-12
    • 2021-05-19
    • 2018-12-27
    • 2021-11-12
    • 2019-09-19
    • 1970-01-01
    • 2016-04-08
    • 2021-08-09
    相关资源
    最近更新 更多