How can I handle exceptions in an http outbound gateway? When i receive status code 500 or 400..., an exception is shown. So What should I do to handle http error using spr
I would like to know why exception does'nt go to reply-channel
Because it's natural to handle exceptions as, er, Exceptions.
There are (at least) two ways to handle exceptions in Spring Integration.
error-channel
and associated flow on whatever starts your flow (e.g. a gateway). The error channel gets an ErrorMessage
with a MessagingException
payload; the exception has two properties - the failedMessage
and the cause
.ExpressionEvaluatingRequestHandlerAdvice
(or a custom advice) to the gateway; see Adding Behavior to Endpoints.If the response status code is in the HTTP series CLIENT_ERROR or SERVER_ERROR, HttpClientErrorException or HttpServerErrorException are thrown respectively. Hence the response doesn't go to reply channel
Refer DefaultResponseErrorHandler
Methods: hasError and handleError
To Handle these exceptions, create your own CustomResponseErrorHandler and override contents of hasError and handlerError methods.
public class CustomResponseErrorHandler extends DefaultResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return hasError(getHttpStatusCode(response));
}
protected boolean hasError(HttpStatus statusCode) {
return /*Status Code to be considered as Error*/ ;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException { /* Handle Exceptions */
}
}
And add error-handler to your http-outbound-gateway
<int-http:outbound-gateway id="quakerHttpGateway"
request-channel="quakeinfotrigger.channel" url="http://fooo/mmmm/rest/put/44545454"
http-method="PUT" expected-response-type="java.lang.String" charset="UTF-8"
reply-timeout="5000" reply-channel="quakeinfo.channel" error-handler="customResponseErrorHandler">
</int-http:outbound-gateway>
I had occurred the same problem.I threw my own customized Exception and error message but always got "500 Internal server error".It's because there will be no reply message and "reply" is timeout when throw Exception.So I handle the exception by subscribing error-channel and then reply by myself.
Message<?> failedMessage = exception.getFailedMessage();
Object replyChannel = new MessageHeaderAccessor(failedMessage).getReplyChannel();
if (replyChannel != null) {
((MessageChannel) replyChannel).send(MessageFactory.createDataExchangeFailMessage(exception));
}