Spring integration: handle http error with oubound gateway

前端 未结 3 1063
星月不相逢
星月不相逢 2021-01-07 12:35

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

相关标签:
3条回答
  • 2021-01-07 13:13

    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.

    1. Add an 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.
    2. Add a ExpressionEvaluatingRequestHandlerAdvice (or a custom advice) to the gateway; see Adding Behavior to Endpoints.
    0 讨论(0)
  • 2021-01-07 13:25

    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>
    
    0 讨论(0)
  • 2021-01-07 13:29

    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));
    }
    
    0 讨论(0)
提交回复
热议问题