Error handling practices in spring integration flow

前端 未结 1 1437
庸人自扰
庸人自扰 2021-02-08 09:33

I have a spring integration flow that involves async execution, returning value from gateway to controller, continuing integration flow after returning a value.

Here is

1条回答
  •  孤城傲影
    2021-02-08 10:31

    First of all, let me explain how the gateway works - it should help with understanding the solution below.

    The request message gets a unique temporary reply channel which is added as the replyChannel header. Even if the gateway has an explicit replyChannel, that is simply bridged to the request's replyChannel - that's how the gateway correlates the reply to the request.

    Now, the gateway also sets the request's errorChannel header to the same reply channel. That way, even if the flow is asynchronous, an exception can be routed back to the gateway and either thrown to the caller or routed to the gateway's error channel (if specified). This routing is performed by a MessagePublishingErrorHandler which is wired into a ErrorHandlingTaskExecutor, which wraps your executor.

    Since you are returning a result to the gateway and then continuing; that gateway interaction is "spent" and nothing will ever receive a message (including an exception) sent to the replyChannel header. Hence the log message you are seeing.

    So, one solution is to fix up the errorChannel header on the message sent to the independent flow. Use .enrichHeaders to replace (be sure to set overwrite to true) the errorChannel header that was set up by the gateway. This should be done as soon as possible in the flow so any exceptions will be routed to that channel (and then you can subscribe your error handler there).

    An alternative solution is to wire up your own error handling executor, explicitly setting a defaultErrorChannel on its MessagePublishingErrorHandler and remove the errorChannel header.

    The async error routing first looks for a header; if present, the error message is routed there; if there's no header and the MPEH has no default error channel; the message will be routed to the default errorChannel to which (normally) there is a LoggingChannelAdapter subscribed. The default errorChannel is a pub/sub channel so you can subscribe other endpoints to it.

    EDIT

    You are changing the channel before the pub/sub.

    It's important to get at least one response to the gateway; you should leave the error channel alone on one leg of the pub/sub and update it on the second leg. That way, an exception on the first leg will be thrown to the caller (you can add an errorChannel to the gateway if you want to take some action there, such as routing to your exception handler). You must only update the header on the second leg so that its exceptions go straight to your error handler.

    If you set the errorChannel on the gateway to your exceptionChannel then exceptions on both legs will go there.

    0 讨论(0)
提交回复
热议问题