2017-08-11 24 views
0

我有一个入站http网关,它的传入消息传递到出站http网关(使用集成java dsl)。春季集成:保留http错误代码和正文作为回应

当出站网关响应的http状态为200时,出站响应将按照预期返回到入站网关的调用者。

但是当出站网关响应特定的客户端错误(如423锁定或403禁止)时,入站网关的调用者会收到500以及包含异常字符串的主体消息。

据我所知,这是因为SI处理出站http错误作为例外。但在我的情况下,我需要将出站响应附带的响应主体的错误状态传回给入站网关的调用者,以了解特定的错误代码。我怎么做?

+0

请,分享堆栈跟踪您看到有错误之前为您服务,即500 –

回答

1

我们称这种情况为HTTP代理和对此事的一些测试用例:https://github.com/spring-projects/spring-integration/blob/master/spring-integration-http/src/test/java/org/springframework/integration/http/dsl/HttpDslTests.java

我只是做了一些调查,以下是你需要什么:

IntegrationFlows 
    .from(Http.inboundGateway("/service") 
      .requestMapping(r -> r.params("name")) 
      .errorChannel("httpProxyErrorFlow.input")) 
... 

@Bean 
public IntegrationFlow httpProxyErrorFlow() { 
    return f -> f 
      .transform(Throwable::getCause) 
      .<HttpClientErrorException>handle((p, h) -> 
        MessageBuilder.withPayload(p.getResponseBodyAsString()) 
          .setHeader(HttpHeaders.STATUS_CODE, p.getStatusCode()) 
          .build()); 
} 

我们必须处理入站网关级别的下游错误。为此,Spring Integration建议使用errorChannel功能。

httpProxyErrorFlow提供了一些关于此事的逻辑。首先我们知道errorChannel的讯息是ErrorMessage,而其​​是MessagingException - 作为将HttpClientErrorException包装在HttpRequestExecutingMessageHandler中的结果。因此,通过.transform()我们可以深入了解所需的例外情况,并在.handle()中根据HttpClientErrorException内容构建新消息。

HttpRequestHandlingMessagingGateway能够正确地处理这样的消息和期望的状态代码设置为响应:

protected final Object setupResponseAndConvertReply(ServletServerHttpResponse response, Message<?> replyMessage) { 
    getHeaderMapper().fromHeaders(replyMessage.getHeaders(), response.getHeaders()); 
    HttpStatus httpStatus = this.resolveHttpStatusFromHeaders(replyMessage.getHeaders()); 
    if (httpStatus != null) { 
     response.setStatusCode(httpStatus); 
    } 

http://docs.spring.io/spring-integration/docs/4.3.11.RELEASE/reference/html/http.html#http-response-statuscode