2

我使用 SpringIntegration-filter 来验证我的 WS 消息。我实现了 Validators 进行验证,如果 WS 消息有效,它们返回 true。但是如果 WS 消息无效,它们会抛出 MyValidationException。

有没有办法使用 SpringIntegration-filter 来处理这种异常?如果我不返回 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();
}
4

2 回答 2

2

Given that the exception is comming from the validate when you check the WS request, you have to surround the call in a try catch. If an exception is thrown, it is catched and false is returned, indicating that the validation failed.

@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));
}

And the helper methods.

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(); 
    }
}
于 2018-03-11T01:21:02.030 回答
1

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

你可以做这样的事情......

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

即分离验证和过滤器关注点。

于 2018-03-12T13:14:14.570 回答