Spring 集成过滤器出现异常

Spring Integration Filter With Exception

我使用 SpringIntegration-filter 来验证我的 WS 消息。我实现验证器来验证,如果 WS 消息有效,它们 return 为真。但如果 WS 消息无效,它们将抛出 MyValidationException。

有没有办法通过使用 SpringIntegration-filter 来处理这个异常?如果我不 return false,过滤器将不起作用。

我的代码示例如下。我想在丢弃流程中使用我的验证异常。

@Bean
public IntegrationFlow incomingRequest() {
    return f -> f
        .<IncomingRequest>filter(message ->
            validatorFactory.validator(message.getName())
                .validate(message),
            filterEndpointSpec -> 
                filterEndpointSpec.discardChannel(discardChannel()))
        .<IncomingRequest>handle((payload, headers) ->
            applicationService.handle(payload));
}

@Bean
public IntegrationFlow discard() {
    return IntegrationFlows.from(discardChannel())
        .log("DISCARD FLOW")
        .get();
}

@Bean(name = "discard.input")
public MessageChannel discardChannel() {
    return MessageChannels.direct().get();
}

鉴于当您检查 WS 请求时异常来自验证,您必须将调用包围在 try catch 中。如果抛出异常,则捕获并返回false,表示验证失败。

@Bean
public IntegrationFlow incomingRequest2() {
    return f -> f
            .filter(this::isValid, filterEndpointSpec -> 
                    filterEndpointSpec.discardFlow(f2 -> f2.transform(this::getReason))
                            .discardChannel(discardChannel()))
            .<IncomingRequest>handle((payload, headers) ->
                    applicationService.handle(payload));
}

和辅助方法。

public boolean isValid(IncomingRequest message) {
    try {
        return validatorFactory.validator(message.getName())
                .validate(message);
    } catch (Exception e) { // your exception
        return false;
    }
}

public String getReason(IncomingRequest message) { // return the object you need
    try {
        validatorFactory.validator(message.getName())
                .validate(message);
        return null;
    } catch (Exception e) { // process exception as you want
        return e.getMessage(); 
    }
}

丢弃通道只是得到被拒绝的入站消息;无法在过滤器中更改它。

你可以这样做...

.handle()   // return an Exception on validation failure
.filter(...) // filter if payload is exception; the exceptions go to the discard channel

即将验证和过滤问题分开。