如何修改Google Apps Script代码优雅处理ETA数据缺失问题?
解决Google Apps Script提取ETA时的TypeError问题
当集装箱无有效ETA数据(如箱号错误、已交付)时,API返回的响应中对应字段未定义,直接访问pod属性会触发Cannot read properties of undefined (reading "pod")错误。可以通过以下两种方式修改代码,实现跳过异常集装箱、继续处理后续数据的需求:
方法一:提前添加空值判断(推荐)
在提取pod属性前,先检查关键对象是否存在,不存在则直接跳过当前集装箱:
// 假设你是在遍历集装箱列表的循环中处理数据 for (let i = 0; i < apiResponse.containers.length; i++) { const container = apiResponse.containers[i]; // 检查集装箱对象及ETA字段是否存在 if (!container || !container.eta) { console.log(`跳过第${i+1}个集装箱:无有效ETA数据`); continue; // 跳出当前循环,处理下一个集装箱 } // 安全提取ETA的pod数据 const etaPod = container.eta.pod; // 后续的ETA更新逻辑... }
这种方式更高效,能主动避免错误发生,适合明确知道可能缺失的字段结构的场景。
方法二:使用try-catch捕获异常
如果不确定哪一步会出现未定义的情况,可以将单个集装箱的处理逻辑包裹在try-catch块中,捕获TypeError时跳过:
for (let i = 0; i < apiResponse.containers.length; i++) { try { // 尝试提取ETA数据及后续处理 const etaPod = apiResponse.containers[i].eta.pod; // 后续的ETA更新逻辑... } catch (error) { // 仅捕获目标TypeError,其他错误正常抛出 if (error instanceof TypeError && error.message.includes('reading "pod"')) { console.log(`跳过第${i+1}个集装箱:${error.message}`); continue; } // 非预期错误,重新抛出以便排查 throw error; } }
这种方式更通用,适合字段结构不确定或可能出现多种异常的场景。
内容的提问来源于stack exchange,提问作者user24015413
相关产品推荐
相关产品推荐

