Solutions BlogGroovy5 min readOctober 2026

Null-safe headers and properties in CPI Groovy scripts

Stop NullPointerExceptions in production by reading headers and exchange properties defensively, with clear errors when data is truly missing.

By the Klynexa integration team

Applies to
SAP Integration Suite, Cloud Integration
Steps involved
Groovy Script
Language
Groovy

The problem

A Groovy script works in testing but fails in production with:

java.lang.NullPointerException: Cannot invoke method toString() on null object

In almost every case, a header or exchange property that was always present in test data is missing for some real messages, and the script assumes it exists.

Root cause

Scripts often read values and immediately call methods on them. When a sender omits a field, a content modifier condition is not met, or an earlier branch skips a step, the value is null and the method call fails. The resulting error tells you nothing about which value was missing.

The solution

Read every value defensively, give optional values a sensible default, and fail early with a clear message when a required value is missing.

import com.sap.gateway.ip.core.customdev.util.Message

def Message processData(Message message) {
    def headers = message.getHeaders()

    // Required: fail clearly if missing
    def orderId = headers.get("OrderId")
    if (!orderId) {
        throw new IllegalStateException(
            "Header OrderId is missing. Check the sender mapping.")
    }

    // Optional: fall back to a default
    def plant = message.getProperty("Plant") ?: "DEFAULT"

    // Safe navigation when calling methods on optional values
    def region = message.getProperty("Region")?.toString()?.toUpperCase()

    message.setProperty("TargetKey", "${plant}-${orderId}".toString())
    if (region) {
        message.setProperty("TargetRegion", region)
    }
    return message
}

Three habits that prevent this class of error

  • Use the Elvis operator ?: for optional values with defaults.
  • Use safe navigation ?. before calling methods on anything that might be missing.
  • Throw an exception that names the missing value, so the monitoring entry explains itself.

Result

Messages with incomplete data either continue with a defined default or fail with a message that names exactly what is missing and where to look. Support time on these incidents drops sharply.