Twilio Functions问题:CPF/CNPJ验证格式化及传值异常排查
问题分析与解决方案:Twilio IVR中CPF/CNPJ格式化函数报错及返回值使用
问题根源
- 参数传递路径错误:你在Run Function Widget里将参数key设为
event,值为{{widget.Inicio.Digits}},这意味着函数接收的event对象里并没有widgets.Inicio.Digits这个嵌套结构——实际传入的是把Digits的值直接绑定到了event.event字段,而非你代码中期望的嵌套路径。 - 未处理空值情况:当代码尝试访问不存在的
event.widgets.Inicio.Digits时,cpfOrCnpj会变为undefined,调用replace方法直接抛出未捕获错误,触发500状态码,而非走到你写的格式校验分支。
修复步骤
1. 调整Run Function Widget的参数配置
将参数的key从event改为明确的名称(比如cpfCnpj),值保持{{widget.Inicio.Digits}}。这样函数就能直接通过event.cpfCnpj获取用户输入的数值。
2. 修正函数代码
调整取值逻辑,同时增加空值判断避免报错:
exports.handler = function(context, event, callback) { // 直接获取传入的参数 const cpfOrCnpj = event.cpfCnpj; // 先检查是否接收到有效数据 if (!cpfOrCnpj) { return callback("Data not received. Please check if the CPF or CNPJ value is being passed correctly"); } const cleanedCpfOrCnpj = cpfOrCnpj.replace(/[^\d]/g, ''); let formatted; if (cleanedCpfOrCnpj.length === 11) { formatted = cleanedCpfOrCnpj.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4'); } else if (cleanedCpfOrCnpj.length === 14) { formatted = cleanedCpfOrCnpj.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, '$1.$2.$3/$4-$5'); } else { return callback("Formato inválido. O valor inserido deve ser CPF (11 dígitos) ou CNPJ (14 dígitos)."); } callback(null, { formattedValue: formatted }); };
在流程其他环节使用函数返回值
Run Function Widget执行成功后,返回的formattedValue会存入流程变量,引用路径为:{{widgets.<你的RunFunctionWidget名称>.formattedValue}}
比如你的Run Function Widget名为validateCPF,后续的Say或其他Widget中,就可以通过{{widgets.validateCPF.formattedValue}}调用格式化后的CPF/CNPJ值。
内容的提问来源于stack exchange,提问作者Leonardo Rubio
相关产品推荐
相关产品推荐

