Checking for null pointer exception in an array in Jenkins scripted pipeline method

Viewed 1086

I am injecting Active Choices parameter value(s) in the Jenkins scripted pipeline.

PFB sample values passed to active choice parameter block:

return['ABC','DEF','GHI',JKL']

PFB my sample script:

node(){
    selectModName()
}

def selectModName(){
    stage 'Multi selection'
    String[] mods = "${modName}".split(',')
    modsz = mods.size()
    echo ''+modsz+''
    for(mod in mods){
        if (modsz == null || modsz == 0){
            echo 'There is nothing to be printed'
        } else {
            echo ''+mod+' is name of the module \n'
        }
    }
}

The else block is executed when I pass greater than or equal to 1 value(s) (working as intended). But if block is not executing its logic when I don't pass any parameter and press build now.

Funny thing is- size() is returning 1 instead of 0 (echo ''+modsz+'') when values aren't passed.

How to make if block execute its logic when no values are passed?

1 Answers

Your code always jumps to the "else" block, because

"".split(',')

produces an array with a single empty string.

assert "".split(',').size() == 1
assert "".splti(',') == [""] as String[]

When you use active choice parameter with multiple values selection and you don't select anything, your variable name stores an empty string. You should check first if the modName parameter is not an empty string and only otherwise split and display values.

node(){
    selectModName()
}

def selectModName(){
    stage 'Multi selection'

    if (modName) {
        String[] mods = modName?.split(',')
        for (mod in mods) {
            echo " ${mod} is name of the module"
        }
    } else {
        echo 'There is nothing to be printed'
    }
}
Related