Scripted Pipeline and Groovy for Jenkins: node, script Blocks, Functions, try/catch and Error Handling

CI CD Pipelines with Jenkins 40 min min read Updated: Nov 17, 2026 Advanced
Scripted Pipeline and Groovy for Jenkins: node, script Blocks, Functions, try/catch and Error Handling
Advanced Topic 4 of 5

Scripted Pipeline Basics

groovy ode('linux') { try { stage('Checkout') { checkout scm } stage('Build') { sh 'mvn -B package' } stage('Test') { sh 'mvn -B test' } currentBuild.result = 'SUCCESS' } catch (err) { currentBuild.result = 'FAILURE' echo "Build failed: ${err}" throw err // re-throw so Jenkins marks the build red } finally { junit allowEmptyResults: true, testResults: 'target/surefire-reports/*.xml' cleanWs() } }
  • No fixed structure: any Groovy is allowed
  • node('label') { } allocates an agent and a workspace. Without node, steps run on the controller in a light way (flyweight), which is fine for echo but not for builds
  • More flexible, but easier to write messy or insecure code. Prefer declarative with small script blocks

Groovy in 10 Minutes

groovy // variables def name = 'shop' int count = 3 def items = ['api', 'web', 'db'] // list def config = [env: 'prod', replicas: 3] // map // string interpolation: only in double quotes echo "Deploying ${name} to ${config.env} with ${config.replicas} replicas" // conditionals if (config.env == 'prod') { echo 'careful' } else if (config.env == 'staging') { echo 'ok' } // loops for (item in items) { echo item } items.each { i -> echo "item ${i}" } (1..3).each { n -> echo "n=${n}" } config.each { k, v -> echo "${k}=${v}" } // functions def greet(String who, String greeting = 'Hello') { return "${greeting}, ${who}" } echo greet('Jenkins') // ternary, elvis, safe navigation def label = count > 2 ? 'many' : 'few' def region = params.REGION ?: 'us-east-1' def len = config.missing?.size()

script Inside Declarative

groovy pipeline { agent any stages { stage('Compute') { steps { script { def version = sh(script: 'cat VERSION', returnStdout: true).trim() def code = sh(script: './check.sh', returnStatus: true) // exit code, does not fail env.APP_VERSION = version if (code != 0) { unstable('check.sh reported warnings') // mark build yellow } echo "Version ${version}" } } } stage('Use it') { steps { sh 'echo $APP_VERSION' } } } }
Step optionEffect
sh(script: '...', returnStdout: true)Returns the command output as text (trim it!)
sh(script: '...', returnStatus: true)Returns the exit code and does not fail the step
unstable('message')Marks the build UNSTABLE
error('message')Stops with FAILURE and a message
currentBuild.result = 'UNSTABLE'Set the result manually

Error Handling

groovy // 1) try/catch: handle and continue stage('Optional lint') { steps { script { try { sh 'npm run lint' } catch (e) { echo "Lint failed but we continue: ${e.message}" currentBuild.result = 'UNSTABLE' } } } } // 2) catchError: mark the stage and the build, but keep going stage('Docs') { steps { catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE', message: 'docs failed') { sh 'make docs' } } } // 3) retry and timeout together retry(3) { timeout(time: 2, unit: 'MINUTES') { sh './flaky-integration.sh' } } // 4) warnError warnError('tests failed') { sh 'make test' }

Parsing Data

groovy script { def info = readJSON file: 'package.json' // pipeline-utility-steps plugin echo "App ${info.name} version ${info.version}" def yaml = readYaml file: 'config.yaml' writeJSON file: 'out.json', json: [build: env.BUILD_NUMBER, result: 'ok'], pretty: 4 def txt = readFile 'notes.txt' writeFile file: 'hello.txt', text: "built ${env.BUILD_NUMBER}" }

Pitfalls: CPS and Serialization

Pipeline code runs in a special engine (CPS) so that builds can survive a Jenkins restart. This brings some rules.

  • Some Java and Groovy objects cannot be saved between steps. Keeping a non-serializable object (for example a Matcher, JsonSlurper result or an iterator) in a variable across a pipeline step causes NotSerializableException
  • Solution: use the pipeline steps (readJSON) or put heavy Groovy in a method marked @NonCPS that returns simple data (strings, lists, maps)
  • Code in @NonCPS methods must not call pipeline steps such as sh or echo
  • .each closures work, but older Groovy versions have limits with some collection methods in CPS. When in doubt use a classic for loop
  • Keep Groovy logic small. Complex logic belongs in a script file (sh './build.sh') or a shared library with tests
groovy @NonCPS def parseVersions(String text) { def result = [] def m = text =~ /(\d+\.\d+\.\d+)/ while (m.find()) { result << m.group(1) } return result // simple list of strings: safe to keep }

Sandbox and Script Approval

  • Pipelines run in a Groovy sandbox that allows only approved methods. If a method is blocked you get *Scripts not permitted*
  • An administrator can approve the signature in *Manage Jenkins, In-process Script Approval*, but approve only what is safe
  • Shared libraries from trusted repositories can run outside the sandbox (see the shared library lesson)
  • Never approve generic methods like Runtime.exec or anything that reads files or environment variables of the controller

Practice Tasks

  1. Rewrite a small declarative pipeline as a scripted one and compare
  2. Write a function that returns a version string, and use it in two stages
  3. Add try/catch/finally that always archives logs and re-throws the error
  4. Use returnStatus to run a check and mark the build UNSTABLE when it returns 2
  5. Cause and fix a NotSerializableException with @NonCPS

Conclusion

Scripted pipelines and script blocks give the full power of Groovy. Learn variables, lists, maps, loops and functions, handle errors with try/catch, catchError, retry and timeout, parse data with readJSON, and avoid CPS serialization pitfalls by keeping Groovy small and using @NonCPS for pure data work.

Quick Summary: scripted node/stage; Groovy basics; script block; returnStdout/Status; unstable/error; catchError/warnError/retry/timeout; readJSON/readYaml; CPS + @NonCPS; sandbox.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators