如何获取响应正文 spring 集成建议

How to get the response body spring integration advice

我有一个出站网关。为了处理异常,我添加了一个建议链,

@ServiceActivator(inputChannel = "channelOutbound")
    @Bean
    public HttpRequestExecutingMessageHandler outboundEpay() {
        final HttpRequestExecutingMessageHandler handler = new HttpRequestExecutingMessageHandler(
                endpoint);
        handler.setExpectedResponseType(String.class);
        handler.setHttpMethod(HttpMethod.PUT);
        handler.setOutputChannelName("channelReply");
        handler.setAdviceChain(Collections.singletonList(advice()));
        return handler;
    }

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

当出站网关returns 200连接的API时,一切正常。但是当 API returns 500 状态时,抛出异常并且连接到“channelAdvice”的服务激活器得到它。但我想获得 API 返回的响应主体以及 500 状态。我应该怎么做才能在建议中得到这样的回应?

@ServiceActivator(inputChannel = "channelAdvice")
    public void activatorAdvice(Message<?> message) {
//HERE
}

DefaultResponseErrorHandlerRestTemplate 中抛出异常时有这样的逻辑:

case SERVER_ERROR:
                throw HttpServerErrorException.create(message, statusCode, statusText, headers, body, charset);

因此,HttpRequestExecutingMessageHandler 抛出的 HttpServerErrorExceptionresponseBody 属性。这就是您从发送到 channelAdvice.

ErrorMessage 中提取错误正文的方法

考虑调试您的 activatorAdvice() 方法以查看 message 参数的内容。

HttpRequestExecutingMessageHandler中的逻辑是:

catch (RestClientException e) {
        throw new MessageHandlingException(requestMessage,
                "HTTP request execution failed for URI [" + uri + "] in the [" + this + ']', e);
    }

因此,ExpressionEvaluatingRequestHandlerAdvice 捕获它并执行此操作以发送 ErrorMessage :

MessagingException messagingException =
                new MessageHandlingExpressionEvaluatingAdviceException(message, "Handler Failed",
                        unwrapThrowableIfNecessary(exception), evalResult);
        ErrorMessage errorMessage = new ErrorMessage(messagingException);
        this.messagingTemplate.send(this.failureChannel, errorMessage);

因此,您的服务激活器的 ErrorMessage 包含 MessageHandlingExpressionEvaluatingAdviceException 作为 payload 并且原因作为 HttpServerErrorException