【问题标题】:How to get the response body spring integration advice如何获得响应体弹簧集成建议
【发布时间】:2021-11-10 05:36:04
【问题描述】:

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

@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;
    }

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

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

【问题讨论】:

    标签: spring-boot spring-integration


    【解决方案1】:

    RestTemplate 抛出异常时,DefaultResponseErrorHandler 有这样的逻辑:

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

    因此,HttpRequestExecutingMessageHandler 抛出的 HttpServerErrorException 具有 responseBody 属性。这是您从发送到您的channelAdviceErrorMessage 中提取错误正文的方法。

    考虑调试您的 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

    【讨论】:

      猜你喜欢
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多