我已经关注了链接Spring integration: handle http error with oubound gateway
但我没有完全理解。
我看了3.实现https://www.baeldung.com/spring-rest-template-error-handling的ResponseErrorHandler,但不知道该怎么做//处理SERVER_ERROR等
我的流程:
休息端点调用网关方法然后在下面。
<int:gateway id="tService"
service-interface="h.lr.eai.TGateway"
default-reply-channel="dest-channel"
default-request-timeout="5000" default-reply-timeout="5000">
<int:method name="vrCorrect" request-channel="tInChannel"/>
<int:method name="...." />
....
</int:gateway>
<int:chain input-channel="tInChannel" output-channel="headerFilterChannel">
<int:header-enricher>
<int:header name="Accept" value="application/json" />
<int:header name="Content-Type" value="application/json" />
</int:header-enricher>
<int-http:outbound-gateway
url="${TURL}/im/rest/something"
http-method="POST"
header-mapper="headerMapper"
error-handler="errorHandler"
expected-response-type="java.lang.String">
</int-http:outbound-gateway>
</int:chain>
<bean id="errorHandler" class="com.util.ErrorHandler" />
java类。以为没有太多的实现,看起来没有这个,我没有得到外部服务抛出的错误消息。
有没有办法可以摆脱这个类,因为它几乎默认[虽然添加了CLIENT和SERVER错误检查,基于baeldung文章?
public class ErrorHandler extends DefaultResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return (
response.getStatusCode().series() == HttpStatus.Series.CLIENT_ERROR
|| response.getStatusCode().series() == HttpStatus.Series.SERVER_ERROR);
}
@Override
public void handleError(ClientHttpResponse response) throws IOException { /* Handle Exceptions */
}
}
我看到使用建议的建议。我可以问一个例子吗? [不确定这是弹簧支架还是弹簧一体化]
编辑1:
我打电话给外部服务。它可以给出如下的错误消息
{
"code": "F01",
"userMessage": "The is some data error....",
"parameters": {}
}
在我将错误处理程序添加到http-outbound-gateway之前,我总是得到响应为“错误请求”[并且错过了如上所述的明确消息]
在添加错误处理程序和类之后,我能够转发外部服务[在其响应主体中]提供的任何错误消息。这是可以接受的,但我在handleError中没有任何实现[就像你回答的那样]。在这种情况下,有没有办法摆脱这个类并利用任何OOTB类?因为我没有理由说明为什么会这样[可能我不明白它的重要性]。
附: @Artem Bilan,你的回答可能就足够了[如果我需要课程来解决我的问题]
不清楚你的问题是什么,但我会尝试解释一些事情。
你肯定可能不需要那个自定义ErrorHandler
,因为默认的一个非常好,最后它只是这样做:
protected void handleError(ClientHttpResponse response, HttpStatus statusCode) throws IOException {
String statusText = response.getStatusText();
HttpHeaders headers = response.getHeaders();
byte[] body = getResponseBody(response);
Charset charset = getCharset(response);
switch (statusCode.series()) {
case CLIENT_ERROR:
throw HttpClientErrorException.create(statusCode, statusText, headers, body, charset);
case SERVER_ERROR:
throw HttpServerErrorException.create(statusCode, statusText, headers, body, charset);
default:
throw new UnknownHttpStatusCodeException(statusCode.value(), statusText, headers, body, charset);
}
}
因此,它解析响应并向调用者抛出相应的异常。
如果在调用REST服务时需要以某种方式对此异常做出反应,则需要考虑使用ExpressionEvaluatingRequestHandlerAdvice
作为<int-http:outbound-gateway>
。这样,从DefaultResponseErrorHandler
传播的异常可以发送到某些failureChannel
,以寻找可能的逻辑如何对此异常作出反应。
请参阅文档中的更多信息:https://docs.spring.io/spring-integration/docs/current/reference/html/#message-handler-advice-chain
如果那不是您所期望的,请重新提出您的问题,因为我还不清楚......
感谢您的理解。