如果处理程序中发生异常,则无法将消息路由到 header 中定义的错误通道

Messages cannot be routed to the error channel defined in header if an exception occurred in handler

两个IntegrationFlow定义如下:

@Bean
public IntegrationFlow myFlow() {
    return IntegrationFlows.from("input.channel")
            .handle("myService", "handle")
            .get();
}

@Bean
public IntegrationFlow exceptionFlow() {
    return IntegrationFlows.from("error.channel")
            .handle(m -> System.out.println(m.getHeaders()))
            .get();
}

MyService的`handle1方法的处理程序只是打印出消息然后抛出异常:

public class MyService {
    public String handle(String s) {
        System.out.println(s);
        throw new RuntimeException("error");
    }
}

在测试中,一条具有定义的错误通道值的消息正好是 error.channel 被放入 input.channelchannel, and it is expected to route to theerror.channel` 通道。

@Test
public void myTest() {
    Message<String> m = MessageBuilder.withPayload("foo").setHeader(MessageHeaders.ERROR_CHANNEL, "error.channel").build();
    this.someInputChannel.send(m);
}

但是,它在测试中抛出异常,并且消息没有路由到错误通道。

这是正确的行为。 errorChannel header 只有在有线程执行器的情况下才会被查询。任何异常都会抛给调用者,因为它是在 Java 中完成的。在 QueueChannelExecutorChannel 的情况下,有一个 MessagePublishingErrorHandler 将任务调用包装到 try..catch 并将 ErrorMessage 发送到 errorChannel header.

在你的情况下,它只是简单的 Java 调用 this.someInputChannel.send(m); ,所以你直接在这个主线程中得到一个异常。

在参考手册中查看更多信息:https://docs.spring.io/spring-integration/docs/current/reference/html/#namespace-errorhandler