我正在尝试验证输入有效负载中的日期和日期时间。如果日期或日期时间格式不正确或为空,我必须验证请求并删除该字段。如果格式正确或空值,它会按预期工作,但如果格式错误,它会抛出错误"不能将a:string强制转换为a:localdatetime">
如何在dwl 1.0 (mule3)中修复这个问题
Input:
{
"date1": "2021-02-12 00:00:00",
"date2": "2021-02-12",
"date3": "2021-02-121",
"date4": "2021-024-123 00:00:00",
"date5": "",
"date6": null
}
Expected Output:
{
"date1": "2021-02-12 00:00:00",
"date2": "2021-02-12",
}
code:
%dw 1.0
%output application/java
%function transformDate(dt) (dt as :date {format: "dd/MM/yyyy"} as :string {format: "yyyy-MM-dd"})
%function changeDateTime(cdt) (cdt as :localdatetime {format: "dd/MM/yyyy HH:mm:ss"} as :string {format: "yyyy-MM-dd'T'HH:mm:ss"})
%function isEmpty(value) (value!=null and value!="")
---
{
(date1: changeDateTime(payload.date1) as :date) when (isEmpty(payload.date1)),
(date2: transformDate(payload.date2) as :localdatetime) when isEmpty(payload.date2),
(date3: transformDate(payload.date3) as :localdatetime) when isEmpty(payload.date3),
(date4: changeDateTime(payload.date4) as :localdatetime) when isEmpty(payload.date4),
(date5: transformDate(payload.date5) as :localdatetime) when isEmpty(payload.date5),
(date6: transformDate(payload.date6) as :localdatetime) when isEmpty(payload.date6)
}
问题是,当尝试用不匹配的模式解析输入日期时,DataWeave会抛出错误:
Message : Exception while executing:
%function changeDateTime(cdt) (cdt as :localdatetime {format: "dd/MM/yyyy HH:mm:ss"} as :string {format: "yyyy-MM-dd'T'HH:mm:ss"})
^
Cannot coerce a :string to a :localdatetime, caused by :Text '2021-02-12 00:00:00' could not be parsed at index 2.
在DataWeave 2/Mule 4中,您有try()函数来测试是否某些表达式失败。不幸的是,在DataWeave 1/Mule 3中没有等效的。作为替代方法,您可以使用以下方法之一:
- 将每个可能失败的表达式隔离到单独的脚本中,并将其封装到可以捕获该表达式的错误处理程序中。
- 使用这篇知识库文章中描述的方法用一个条件保护每个模式转换,并在尝试模式转换之前尝试测试模式是否匹配。示例
(dateStr) -> dateStr as :localdatetime {format: "E, d LLL u H:m:s O"} when (dateStr contains /^[A-z][A-z][A-z],/) otherwise (dateStr as :localdatetime {format: "E LLL d H:m:s u"} when (dateStr contains /^[A-z][A-z][A-z]s/) otherwise dateStr as :localdatetime {format: "cccc, d-LLL-u H:m:s O"})