typescript - 在将 Azure 函数 EventHub 触发器升级到编程模型 v4 时出现错误。这是否与缺少设置 "dataType": "binary" 有关?
我正在尝试将我的 Azure 函数从 v3 编程模型迁移到 v4 编程模型。如果我尝试触发重构后的函数,会出现以下错误:
[2023-10-24T08:05:30.375Z] Executed 'Functions.location-updates' (Failed, Id=caeb8080-79aa-4230-b7f7-541111ef99bb, Duration=65ms)
[2023-10-24T08:05:30.375Z] System.Private.CoreLib: Exception while executing function: Functions.location-updates. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'eventHubTrigger1'. Microsoft.Azure.WebJobs.Host: Binding parameters to complex objects (such as 'Object') uses Json.NET serialization.
[2023-10-24T08:05:30.375Z] 1. Bind the parameter type as 'string' instead of 'Object' to get the raw values and avoid JSON deserialization, or
[2023-10-24T08:05:30.376Z] 2. Change the queue payload to be valid json. The JSON parser failed: Unexpected character encountered while parsing value: . Path '', line 0, position 0.
在编程模型 v3 中,我在 function.json 文件中指定了 "dataType": "binary",但在 v4 中,这在 app.eventHub(name, options) 的选项中不可行。我认为这可能是导致错误的原因。
谢谢你的帮助!
答案#1
在 V4 中,以前在 function.json 文件中指定的触发器配置,如方法和 AuthLevel、数据类型,已移到代码本身。
已经有一些变化,不再使用“dataType: binary”。
事件中心触发器默认期望将消息反序列化为 JSON。如果你的事件中心消息不是 JSON 格式,你将需要自己处理反序列化。
为此,您应将参数绑定为字符串,然后在函数代码中手动反序列化消息。
module.exports = async function (context, eventHubMessages) {
for (const message of eventHubMessages) {
// For example, if the message is a binary format, you can decode it to a string
const decodedMessage = Buffer.from(message, 'base64').toString('utf8');
// Now you can work with the decoded message as a string
context.log(decodedMessage);
}
};
在 v4 中,将参数绑定为字符串,并在消息不是 JSON 格式时手动处理反序列化。更多详情请参考此链接。
