使用Lex V2平台+Node.js Lambda对接ServiceNow创建事件时出现Invalid Lambda Response及Cannot read property 'name' of undefined错误的解决咨询
解决Lex V2 + Lambda Node.js TypeError及424错误的思路
首先,你遇到的TypeError: Cannot read property 'name' of undefined是典型的访问未定义变量属性的问题,结合你用Lex V2控制台但代码由前同事编写的背景,大概率是代码适配的是Lex V1的请求格式,而Lex V2的事件结构和V1完全不同导致的。下面是具体的排查和解决步骤:
1. 定位代码中的问题点
找到/var/task/index.js第7行第38位的代码,查看这一行正在访问哪个对象的.name属性。最常见的情况是:
- 代码里写了类似
const intentName = event.currentIntent.name;(Lex V1的写法) - 但Lex V2的请求中,意图信息是放在
event.sessionState.intent下的,不存在currentIntent字段,所以event.currentIntent是undefined,访问它的.name就会抛出这个错误。
2. 适配Lex V2的事件结构
Lex V2和V1的请求格式差异很大,你需要把代码中所有基于V1的路径替换成V2的规范:
- 意图名称:从
event.currentIntent.name改成event.sessionState.intent.name - 槽位值:V1中槽位值是
event.currentIntent.slots.shortDesc,而V2中是event.sessionState.intent.slots.shortDesc?.value?.originalValue(针对文本类型槽位,?.是可选链操作符,能避免槽位未填充时再次出现undefined错误) - 意图状态:V2中意图状态在
event.sessionState.intent.state,你已经确认是ReadyForFulfillment,这部分是正常的。
举个简单的适配示例:
// 原Lex V1风格代码 const intentName = event.currentIntent.name; const shortDesc = event.currentIntent.slots.shortDesc; // 修改为Lex V2兼容代码 const intentName = event.sessionState.intent.name; const shortDesc = event.sessionState.intent.slots.shortDesc?.value?.originalValue;
3. 先解决TypeError,再处理424错误
Chrome控制台的424错误(依赖失败)是因为Lambda函数执行抛出了TypeError,导致Lex无法正常获取 fulfillment 结果。所以优先修复TypeError:
- 修复代码后重新部署Lambda函数
- 测试机器人,查看CloudWatch日志确认TypeError是否消失
- 如果还有错误,再排查Lambda调用ServiceNow API的细节:比如API地址是否正确、认证信息是否有效、请求体格式是否符合ServiceNow的要求
4. 调试技巧
如果还是不确定问题,可以在Lambda代码中添加日志输出辅助排查:
- 在出错代码行之前,打印整个event对象:
console.log('Received Lex event:', JSON.stringify(event, null, 2)); - 打印你要访问的变量:
console.log('Intent object:', event.sessionState.intent); - 查看CloudWatch日志中的这些输出,确认变量是否存在、结构是否符合预期
内容的提问来源于stack exchange,提问作者sas
相关产品推荐
相关产品推荐

