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

如何在Jenkinsfile中判断BUILD_USER_EMAIL等属性是否存在以避免报错

Jenkins BuildUser变量缺失异常修复方案

groovy.lang.MissingPropertyException异常的核心原因是:自动触发构建时BuildUser插件不会向脚本上下文注入BUILD_USER_EMAIL变量,直接引用未定义的绑定变量会触发Groovy语法层面的报错,不会按布尔判断的预期返回空值。

修复方案1:先判断变量是否存在再引用

通过binding.hasVariable()方法先校验当前脚本上下文是否存在对应变量,确认存在后再做非空判断,兼容性最高:

def function() {
    wrap([$class: 'BuildUser']) {
        script {
            def triggeredBy = "Jenkins"
            if (binding.hasVariable('BUILD_USER_EMAIL') && BUILD_USER_EMAIL) {
              triggeredBy = "<mention email='${BUILD_USER_EMAIL}'/>"
            }
        }
    }
}

修复方案2:从env环境变量对象取值

将变量作为env的属性读取,环境变量对象中不存在的属性会直接返回null,不会抛出异常,写法更简洁:

def function() {
    wrap([$class: 'BuildUser']) {
        script {
            def triggeredBy = "Jenkins"
            if (env.BUILD_USER_EMAIL) {
              triggeredBy = "<mention email='${env.BUILD_USER_EMAIL}'/>"
            }
            // 也可以用三目运算符简化为一行
            // def triggeredBy = env.BUILD_USER_EMAIL ? "<mention email='${env.BUILD_USER_EMAIL}'/>" : "Jenkins"
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:09:02