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

问题描述 投票:0回答:1

我正在尝试使用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用作全局异常处理程序,但这不是我的意图。

spring-integration spring-integration-dsl
1个回答
0
投票

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

作为一种解决方法,建议您查看ExpressionEvaluatingRequestHandlerAdvicetransform()https://docs.spring.io/spring-integration/docs/current/reference/html/messaging-endpoints.html#message-handler-advice-chain

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

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

© www.soinside.com 2019 - 2024. All rights reserved.