0

我正在尝试抑制从 http 出站网关为非 2XX 状态代码生成的 MessageHandlingException,并优雅地将控制权返回给父流,以便在成功流中按照预期在回复通道上返回具有原始有效负载的消息。

原始代码:

 @Bean
  public IntegrationFlow inquiry() {
    return flow -> flow
    .handle(Http
                .outboundGateway("url", restTemplate)
                .mappedRequestHeaders("*")
                .headerMapper(headerMapper)
                .extractPayload(true)
                .httpMethod(HttpMethod.POST)
                .expectedResponseType(expectedResponseType.class)
            )

我尝试使用errorHandlerHttp,但它提供了客户端响应的句柄,并且原始有效负载不是其中的一部分。

也尝试过表达建议路线。

@Bean
  public IntegrationFlow inquiry() {
    return flow -> flow
    .handle(Http
                    .outboundGateway("url", restTemplate)
                    .mappedRequestHeaders("*")
                    .headerMapper(headerMapper)
                    .extractPayload(true)
                    .httpMethod(HttpMethod.POST)
                    .expectedResponseType(expectedResponseType.class)
                , c->c.advice(expresionAdvice())) 

如果没有成功和失败通道,建议不会将控制权归还,但目的是将控制权归还给父级。

可能最简单的方法是用 .handle 包装try.. catch并捕获 MessageHandlingException 并将其传播@ExceptionHandler并转换它。

有没有办法可以用建议或errorChannel来完成,在@MessagingGatewayhttp出站网关的404之后没有调用它的errorChannel。

上面的代码是另一个流程的一部分,我正在独立测试这个流程。

集成流中是否存在错误通道?

更新1:

能够弄清楚为什么 errorChannel on@MessagingGateway没有从测试中被调用,它仅在调用完整流时才被调用,而不是仅inquiry()使用 DirectChannel 的方法。

现在 errorChannel 正在工作,使用异常之前的有效负载状态设置自定义标头,并从 failedMessage 标头中访问它。

它现在按预期工作,并且永远不会向响应中抛出错误。感觉这是一个解决方法..

有没有办法在建议中更好地处理这个问题?

编辑1:

代码不完整我试图让它工作

@Bean
  public Advice expressionAdvice() {
    ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice();
    advice.setOnSuccessExpressionString("payload");
    advice.setOnFailureExpressionString("payload");
    advice.setTrapException(true);
    return advice;
  }

由于我没有从建议中指定通道流,因此流无处可去,需要一些类似的东西,.defaultOutputToParentFlow() 以便它使用Message.

回答 :

它有效,但唯一的问题是,我仍然需要自定义标头来获取原始有效负载,而不是请求失败有效负载/正文才能继续进程。

@Bean
  public Advice expressionAdvice() {
    ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice();
    advice.setOnSuccessExpressionString("payload");
    advice.setOnFailureExpressionString("headers['CUSTOM_KEY']");
    advice.setTrapException(true);
    advice.setReturnFailureExpressionResult(true);
    return advice;
  }

这就是我正在寻找的。可能会更改变量名称,因为建议将返回成功,而不仅仅是失败案例。

4

1 回答 1

0

您还需要ExpressionEvaluatingRequestHandlerAdvice对此进行配置true

/**
 * If true, the result of evaluating the onFailureExpression will
 * be returned as the result of AbstractReplyProducingMessageHandler.handleRequestMessage(Message).
 *
 * @param returnFailureExpressionResult true to return the result of the evaluation.
 */
public void setReturnFailureExpressionResult(boolean returnFailureExpressionResult) {
    this.returnFailureExpressionResult = returnFailureExpressionResult;
}
于 2018-09-19T13:33:19.883 回答