我们将此场景称为 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
isErrorMessage
和它的消息payload
是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