How to resolve "java.lang.NullPointerException: Cannot invoke method startsWith()"?

6.7k Views Asked by At

I am new to groovy. I am writing a shared library for Jenkins pipeline. I am facing this java.lang.NullPointerException exception. Below is my code:

def call(Map config = [:], env) {
    
            pipeline {
                defaults = [
                        'pipelineStrategy'          : 'deployOnly',
                        'buildSystem'               : 'maven'
                ] + config
        
                environment {
                    BRANCH_NAME = "${GIT_BRANCH.split("/")[1]}"
                }
                boolean autoDeploy = false;
                if (env.BRANCH_NAME.equals('master') || env.BRANCH_NAME.startsWith('hotfix-')){
                    autoDeploy = true;
                }
        }
}

Below are my Jenkins build logs:

java.lang.NullPointerException: Cannot invoke method startsWith() on null object
    at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:91)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:48)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:35)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.methodCall(DefaultInvoker.java:20)
    at pipelineStrategy.call(pipelineStrategy.groovy:21)
2

There are 2 best solutions below

0
On

The only startsWith() in the code you posted is in

env.BRANCH_NAME.startsWith('hotfix-')

and you are being told that there is a null object. It means that

env.BRANCH_NAME

is null. You will need to think why or how to handle that situation. One way might be to use

String.valueOf(env.BRANCH_NAME).startsWith('hotfix-')
0
On

You are probably trying to use a multibranch pipeline syntax on a "non-multibranch pipeline"...

This variable is available only for multibranch pipelines.