如何使用自定义错误通道来产生自定义错误响应?

时间:2020-05-10 21:02:18

标签: spring-integration spring-integration-dsl

我正在尝试使用Spring Integration构建一个简单的API。对于API中引发的任何异常或错误,我想向客户端提供自定义错误响应。我正在尝试以下流程结构:

@Bean
public IntegrationFlow mainFlow() {
    return IntegrationFlows.from(WebFlux.inboundGateway(path)
            .errorChannel(customErrorChannel())
        )
        .enrichHeaders(h -> h.header(MessageHeaders.ERROR_CHANNEL, "customErrorChannel"))
        .transform(p -> {
            if(<some validation fails>)
                throw new RuntimeException("Error!");
            return "Ok Response";
        })
        .get();
}

@Bean
public PublishSubscribeChannel customErrorChannel() {
    return MessageChannels.publishSubscribe().get();
}

@Bean
public IntegrationFlow errorFlow() {
    return IntegrationFlows.from("customErrorChannel")
        .transform(p -> {
            return "Error Response";
        })
        .get();
}

对于成功案例,将“确定响应”提供给客户端。但是,当在转换器中引发异常时,提供的响应是来自具有堆栈跟踪的框架的默认错误响应。如何使用errorFlow对异常做出最终回应?

我可以使用CustomErrorWebExceptionHandler作为全局异常处理程序,但这不是我的意图。

1 个答案:

答案 0 :(得分:1)

事实证明,在像.errorChannel(customErrorChannel())这样的反应性通道适配器的情况下,WebFlux.inboundGateway()不再使用。请提出一个GH问题,我们将考虑如何以及如何做。

作为一种解决方法,我建议您针对ExpressionEvaluatingRequestHandlerAdvicehttps://docs.spring.io/spring-integration/docs/current/reference/html/messaging-endpoints.html#message-handler-advice-chain来研究transform()

这样,您将捕获转换器中的所有错误,并将其发送到customErrorChannel进行处理。

.enrichHeaders(h -> h.header(MessageHeaders.ERROR_CHANNEL, "customErrorChannel"))中没有任何理由。 .errorChannel(customErrorChannel())应该足够了。但是当我们已经有了修复程序时。

更新

作为一种变通办法,可以在.channel(MessageChannels.flux())之前添加transform(),并且应该通过errorChannel处理错误。