并行流中缺少异常详细信息

问题描述 投票:3回答:2

在大多数情况下,并行流中引发的异常不会具有其所有属性。

Ex:

@Test
public void test() {
    assertThatThrownBy(() -> Stream.of("1", "2", "asdf").parallel().forEach(Integer::parseInt))
            .asInstanceOf(InstanceOfAssertFactories.type(NumberFormatException.class))
            .extracting("detailMessage")
            .isEqualTo("For input string: \"asdf\"");
}

这通常会失败,而这:

@Test
public void test() {
    assertThatThrownBy(() -> Stream.of("1", "2", "asdf").forEach(Integer::parseInt))
            .asInstanceOf(InstanceOfAssertFactories.type(NumberFormatException.class))
            .extracting("detailMessage")
            .isEqualTo("For input string: \"asdf\"");
}

成功率100%。

另一件事是,当消息不存在时,它将出现在异常原因中。例如:

@Test
public void test() {
    assertThatThrownBy(() -> Stream.of("1", "2", "asdf").parallel().forEach(Integer::parseInt))
            .asInstanceOf(InstanceOfAssertFactories.type(NumberFormatException.class))
            .extracting("cause.detailMessage")
            .isEqualTo("For input string: \"asdf\"");
}

关于如何使并行流抛出精确和异常而不是某种嵌套怪物的任何想法?

java java-8 java-stream assertj
2个回答
0
投票

[也许您收到的异常是由parallel()引发的另一种异常包装的,包含更多信息,而您正在寻找的实际异常是getCause()getSupperessed()

外部异常所具有的附加信息可以是流中通过异常而产生的项目数量(例如,“ 3之1”)或类似的东西。


0
投票

我无法解释为什么当您使用assertThatThrownBy时它不起作用,但是如果您想使用JUnit,我可以给您一个解决方法。这两个测试均通过:

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void test() {
    thrown.expect(NumberFormatException.class);
    thrown.expectMessage("For input string: \"asdf\"");
    Stream.of("1", "2", "asdf").forEach(Integer::parseInt);
}


@Test
public void testParallel() {
    thrown.expect(NumberFormatException.class);
    thrown.expectMessage("For input string: \"asdf\"");
    Stream.of("1", "2", "asdf").parallel().forEach(Integer::parseInt);
}
© www.soinside.com 2019 - 2024. All rights reserved.