如何创建PredicateExceptionFactory处理Apache Camel的PredicateValidationException
解决方案:将PredicateValidationException转为自定义异常
1. 定义自定义异常类
如果还未创建自定义异常,先实现如下类:
public class CustomValidationFailed extends RuntimeException { public CustomValidationFailed(String message) { super(message); } }
2. 创建PredicateExceptionFactory Spring Bean
创建配置类,实现PredicateExceptionFactory接口并注册为Spring Bean,Camel会自动使用该工厂生成自定义异常,替代默认的PredicateValidationException:
import org.apache.camel.support.processor.PredicateExceptionFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CamelValidationConfig { @Bean public PredicateExceptionFactory customPredicateExceptionFactory() { // 可根据校验场景定制异常消息 return (exchange, predicate, errorMessage) -> new CustomValidationFailed(errorMessage); } }
3. 优化异常消息(可选)
如果需要针对特定校验逻辑生成精准消息,比如你的offerId校验,可以调整工厂逻辑:
@Bean public PredicateExceptionFactory customPredicateExceptionFactory() { return (exchange, predicate, errorMessage) -> { String targetMessage = errorMessage.contains("offerId") ? "offerId should be provided" : "Validation failed: " + errorMessage; return new CustomValidationFailed(targetMessage); }; }
原理说明
默认情况下,Camel的validate处理器会抛出PredicateValidationException(对应500状态码)。通过注册PredicateExceptionFactory Bean,你可以接管异常创建逻辑,替换为自定义异常,这样原有路由中配置的onException(CustomValidationFailed.class)就能正确捕获异常,返回400 Bad Request响应。
内容的提问来源于stack exchange,提问作者Eli m
相关产品推荐
相关产品推荐

