gpt4 book ai didi

java - 即使在 @Converter 注释中将 allowNull 设置为 true,Camel TypeConverter 仍会抛出 NoTypeConversionAvailableException

转载 作者:行者123 更新时间:2023-12-02 18:39:15 26 4
gpt4 key购买 nike

我正在使用 Apache Camel 3.4.3 并尝试为我的 Camel 路线转换空值

     from(endpointURI)
.convertBodyTo(DataContainer.class)
.to(DIRECT_ROUTE)

像这样使用自定义类型转换器:

@Converter(allowNull = true)
public DataContainer toDataContainer(String xml) {
LOGGER.info("Received body as string [{}] try to convert to DataContainer", xml);
if (StringUtils.isBlank(xml)) {
return null;
}
if (!XmlUtils.isXml(xml)) {
throw new SwiftCorpException(ErrorCode.ERROR_99999,
String.format(
"value [%s] is not a xml, so it cannot be converted to DataContainer",
xml
)
);
}
return DataContainer.fromXml(xml);
}

但是这种方式会引发异常:

org.apache.camel.InvalidPayloadException: No body available of type: ru.swiftcorp.common.utils.DataContainer but has value: of type: java.lang.String on: Message. Caused by: No type converter available to convert from type: java.lang.String to the required type: ru.vtb.swiftcorp.common.utils.DataContainer with value . Exchange[]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: java.lang.String to the required type: ru.swiftcorp.common.utils.DataContainer with value ]

我开始调试,发现当@Converter注解中的allowNull设置为true时,会导致执行下面的代码进入CoreTypeConverterRegistry方法内部类 public <T> T mandatoryConvertTo(Class<T> type, Exchange exchange, Object value) throws NoTypeConversionAvailableException :

public <T> T mandatoryConvertTo(Class<T> type, Exchange exchange, Object value) throws NoTypeConversionAvailableException {

...
Object answer = doConvertTo(type, exchange, value, true, false);
if (answer == null) {
// Could not find suitable conversion
throw new NoTypeConversionAvailableException(value, type);
}
return (T) answer;
}

此处的answer 为空,下一步将抛出 NoTypeConversionAvailableException。

但是 Apache Camel 说下一个 (here's a link) :

If null should be allowed as a valid response, then from Camel 2.11.2/2.12 onwards you can specify this in the annotation as shown

所以我的问题是如何在类型转换器中返回 null(我可以这样做)值,以便我的路由不会在转换发生的地方中断吗?

最佳答案

这是因为convertBodyTo使用的是强制转换,也就是说如果不能转换就会抛出异常。

您可以争辩说 allowNull 即使对于强制转换也应该是有效的。然而,这不是它的原始设计,因为它是用于常规转换(不是强制性的)。作为强制性的是保证始终存在该给定类型的响应对象(它永远不会为空)的契约(Contract)。

当您有后备转换器时,还引入了 allowNull,这些转换器可能会或可能不会根据输入数据的内容进行转换。

需要多考虑一下,我们是否应该放宽 convertBodyTo 为非强制性的,或者添加一个标志以便您可以打开|关闭强制性

关于java - 即使在 @Converter 注释中将 allowNull 设置为 true,Camel TypeConverter 仍会抛出 NoTypeConversionAvailableException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68272284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com