You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

访问AWS SSM参数值时出现Cannot read property 'Value' of undefined错误的解决方法

解决AWS SSM参数访问时的TypeError: Cannot read property 'Value' of undefined错误

问题核心原因

你遇到的错误是因为异步操作处理不当:ssm.getParameter().promise()返回的是一个Promise对象,而非直接的SSM参数查询结果。你直接用data.Parameter.Value访问时,data是Promise实例,根本不存在Parameter属性,因此触发了TypeError。

另外代码还有两处细节问题:

  • JSON.srtingify拼写错误,正确写法是JSON.stringify
  • 未处理SSM调用失败的场景(比如参数不存在、权限不足)

修复后的代码实现

方案1:使用async/await(推荐)

将handler改为async函数,用await等待Promise解析,同时添加异常捕获逻辑:

exports.handler = async (event, context, callback) => {
    const request = event.Records[0].cf.request;
    const headers = request.headers;
    const ssm = new (require('aws-sdk/clients/ssm'))();

    try {
        // 等待SSM参数查询完成,获取实际返回数据
        const data = await ssm.getParameter({
            Name: '/dev/cdn/test',
            WithDecryption: true
        }).promise();

        console.log(data.Parameter.Value);
        if (data.Parameter.Value === 'Down') {
            const redirectResponse = {
                status: '503',
                statusDescription: 'Service Unavailable'
            };
            console.log(JSON.stringify(redirectResponse));
            callback(null, redirectResponse);
        } else {
            // 参数值非Down时,返回原始请求
            callback(null, request);
        }
    } catch (error) {
        // 处理SSM调用失败的情况
        console.error('SSM参数查询失败:', error);
        // 可根据需求返回原始请求或错误响应
        callback(null, request);
    }
};

方案2:使用Promise链式回调

如果无法使用async/await(比如Node.js版本过低),可以用Promise的then/catch处理:

exports.handler = (event, context, callback) => {
    const request = event.Records[0].cf.request;
    const headers = request.headers;
    const ssm = new (require('aws-sdk/clients/ssm'))();

    ssm.getParameter({
        Name: '/dev/cdn/test',
        WithDecryption: true
    }).promise()
    .then(data => {
        console.log(data.Parameter.Value);
        if (data.Parameter.Value === 'Down') {
            const redirectResponse = {
                status: '503',
                statusDescription: 'Service Unavailable'
            };
            console.log(JSON.stringify(redirectResponse));
            callback(null, redirectResponse);
        } else {
            callback(null, request);
        }
    })
    .catch(error => {
        console.error('SSM参数查询失败:', error);
        callback(null, request);
    });
};

内容的提问来源于stack exchange,提问作者Girish Adoni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:15:34