overexchange
overexchange

Reputation: 1

How to catch exception in groovy?

In the below code:

def build(arg1, arg2, arg3, arg4, arg5){

    try{

        executeBuildCommand(commandString, component)
    }
    }catch(Exception e){

        print ' build() method raised exception'
        print "Error cause: ${e}"
        error('Build stage - failed')
    }
}


def executeBuildCommand(arg1, arg2){

    try{
        // BUILD_FULL = sh('build the code')

        if(BUILD_FULL == true){
            def data = new URL(${BUILD_URL}).getText()
        }        
    }catch(Exception e){
        throw e
    }   
}

I understand that "${BUILD_URL}" interpolates in runtime

But catch block in build() method, does not catch exception thrown on line(def data = new URL(${BUILD_URL}).getText())

instead I receive exception stack

java.lang.NoSuchMethodError: No such DSL method '$' found among steps [ArtifactoryGradleBuild, MavenDescriptorStep, acceptGitLabMR, 
addGitLabMRComment, addInteractivePromotion, ansiColor, archive, artifactoryDistributeBuild,... ]  or 
globals [Artifactory, LastChanges, currentBuild, docker, env, params, pipeline, scm]
    at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:201)
    at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)

How to handle exceptions?

Upvotes: 3

Views: 42202

Answers (1)

Dmitry Khamitov
Dmitry Khamitov

Reputation: 3276

There are at least two problems in your executeBuildCommand:

  1. new URL(${BUILD_URL}) means that you are trying to call some method $ which has a closure as the only argument. You certainly wanted it to look like new URL("${BUILD_URL}") in order to interpolate BUILD_URL. Or why not use just new URL(BUILD_URL)?
  2. As a result of point 1, you get java.lang.NoSuchMethodError for $. But you try to catch Exception which is not a superclass of NoSuchMethodError. The latter has java.lang.Error as a superclass. If you had tried catching an Error you'd have seen your messages

Upvotes: 4

Related Questions