DataWeave is powerful but produces cryptic errors. This guide decodes the most common DataWeave errors and provides tested solutions.
Error: Cannot Coerce :null to :object
Symptom:
Cannot coerce Null (null) to Object
org.mule.weave.v2.exception.MuleWeaveException: Cannot coerce Null (null) to Object
Cause: Accessing properties on a null value or null payload.
Solution 1 - Null-safe navigation:
%dw 2.0
output application/json
---
// ❌ Fails if payload is null
{
name: payload.customer.name
}
// ✅ Null-safe with default
{
name: payload.customer.name default "Unknown"
}
// ✅ Full null-safe chain
{
name: (payload.customer default {}).name default "Unknown"
}
// ✅ Using unless-otherwise
{
name: payload.customer.name unless payload.customer == null otherwise "Unknown"
}Solution 2 - Conditional check:
%dw 2.0
output application/json
---
if (payload != null and payload.customer != null)
{ name: payload.customer.name }
else
{ name: "N/A" }Error: Cannot Coerce :string to :number
Symptom:
Cannot coerce String "abc" to Number
You called the function '+' with these arguments: String, Number
Cause: Performing numeric operations on string values.
Solution - Explicit type conversion:
%dw 2.0
output application/json
---
{
// ❌ Fails if quantity is string "10"
total: payload.quantity * payload.price,
// ✅ Convert to number first
total: (payload.quantity as Number default 0) * (payload.price as Number default 0),
// ✅ With validation
total: if (payload.quantity is Number and payload.price is Number)
payload.quantity * payload.price
else
0
}Safe numeric conversion function:
%dw 2.0
output application/json
fun safeNumber(value) =
if (value is Number) value
else if (value is String and value matches /^-?\d+\.?\d*$/)
value as Number
else 0
---
{
amount: safeNumber(payload.amount)
}Error: Unable to Parse JSON/XML
Symptom:
Unable to read JSON at 1:1
Exception while executing parse: Expected a json value
Unexpected character '<' at index 0
Cause: Content type mismatch or malformed data.
Solution 1 - Force correct MIME type:
%dw 2.0
output application/json
---
// When payload is string containing JSON
read(payload, "application/json")
// When payload is string containing XML
read(payload, "application/xml")Solution 2 - Handle mixed content:
%dw 2.0
output application/json
fun tryParseJson(content) =
try(read(content, "application/json")) orElse null
fun tryParseXml(content) =
try(read(content, "application/xml")) orElse null
---
{
data: tryParseJson(payload) default tryParseXml(payload) default payload
}Solution 3 - Clean BOM and whitespace:
%dw 2.0
output application/json
---
// Remove BOM and leading/trailing whitespace
read(trim(payload replace /^\uFEFF/ with ""), "application/json")Error: Scripting Error - Heap Space
Symptom:
java.lang.OutOfMemoryError: Java heap space
org.mule.weave.v2.exception.MuleWeaveException: Max output size exceeded
Cause: Processing large payloads or inefficient transformations.
Solution 1 - Enable streaming:
%dw 2.0
output application/json deferred=true
---
payload map ((item) -> {
id: item.id,
name: item.name
})Solution 2 - Use streaming in Mule config:
<ee:transform doc:name="Transform">
<ee:message>
<ee:set-payload>
<![CDATA[
%dw 2.0
output application/json streaming=true
---
payload
]]>
</ee:set-payload>
</ee:message>
</ee:transform>Solution 3 - Batch processing pattern:
%dw 2.0
output application/json
var batchSize = 1000
var totalBatches = ceil(sizeOf(payload) / batchSize)
---
(1 to totalBatches) map ((batchNum) ->
payload[(batchNum - 1) * batchSize to batchNum * batchSize - 1]
)Error: Key Already Present
Symptom:
Duplicate key 'name' found at selector 'name'
Cause: Object has duplicate keys (common when merging).
Solution - Handle duplicates explicitly:
%dw 2.0
output application/json
// Merge objects, last value wins
fun mergeObjects(obj1, obj2) =
obj1 ++ obj2
// Merge with custom conflict resolution
fun mergeWithPriority(obj1, obj2) =
(obj1 -- keysOf(obj2)) ++ obj2
---
{
result: mergeWithPriority(payload.defaults, payload.overrides)
}Error: Index Out of Bounds
Symptom:
Index 5 out of bounds for length 3
java.lang.ArrayIndexOutOfBoundsException
Cause: Accessing array index that doesn't exist.
Solution - Safe array access:
%dw 2.0
output application/json
---
{
// ❌ Fails if array has less than 3 items
thirdItem: payload.items[2],
// ✅ Safe access with default
thirdItem: payload.items[2] default null,
// ✅ Check length first
thirdItem: if (sizeOf(payload.items default []) > 2)
payload.items[2]
else
null,
// ✅ Safe first/last
firstItem: payload.items[0] default null,
lastItem: payload.items[-1] default null
}Error: Date Parsing Failed
Symptom:
Unable to parse '2025-13-45' as Date
Text '2025/01/15' could not be parsed at index 4
Cause: Date format mismatch or invalid date.
Solution - Flexible date parsing:
%dw 2.0
output application/json
fun parseFlexibleDate(dateStr) =
if (dateStr == null) null
else if (dateStr matches /^\d{4}-\d{2}-\d{2}$/)
dateStr as Date {format: "yyyy-MM-dd"}
else if (dateStr matches /^\d{2}\/\d{2}\/\d{4}$/)
dateStr as Date {format: "MM/dd/yyyy"}
else if (dateStr matches /^\d{4}\/\d{2}\/\d{2}$/)
dateStr as Date {format: "yyyy/MM/dd"}
else
try(dateStr as Date) orElse null
fun safeDateFormat(date, format) =
if (date != null)
date as String {format: format}
else
null
---
{
parsedDate: parseFlexibleDate(payload.dateString),
formatted: safeDateFormat(parseFlexibleDate(payload.dateString), "yyyy-MM-dd")
}Error: Encoding Issues (UTF-8)
Symptom:
MalformedInputException: Input length = 1
Unmappable character for encoding UTF-8
Cause: Invalid characters or wrong encoding.
Solution - Force encoding:
%dw 2.0
output application/json encoding="UTF-8"
---
// Clean problematic characters
payload.text replace /[\x00-\x08\x0B\x0C\x0E-\x1F]/ with ""In Mule flow - set encoding:
<set-payload value="#[payload]" mimeType="application/json; charset=UTF-8"/>Error: Maximum Call Stack Exceeded
Symptom:
Stack overflow
Maximum call stack size exceeded in recursive function
Cause: Infinite recursion or deep nesting.
Solution - Tail recursion or iteration:
%dw 2.0
output application/json
// ❌ Regular recursion (can overflow)
fun flattenBad(arr) =
arr flatMap ((item) ->
if (item is Array) flattenBad(item)
else [item]
)
// ✅ Use built-in flatten with depth limit
fun flattenSafe(arr, maxDepth = 10) =
if (maxDepth <= 0) arr
else flatten(arr map ((item) ->
if (item is Array) flattenSafe(item, maxDepth - 1)
else [item]
))
---
{
flattened: flattenSafe(payload.nestedArray)
}DataWeave Debugging Techniques
Log intermediate values:
%dw 2.0
output application/json
import * from dw::Runtime
var step1 = payload.data
var logged1 = log("Step 1", step1)
var step2 = step1 filter ($.active == true)
var logged2 = log("Step 2", step2)
---
step2Try-catch pattern:
%dw 2.0
output application/json
---
{
result: try(() -> riskyOperation(payload))
.success
default "Operation failed",
error: try(() -> riskyOperation(payload))
.error.message
default null
}Type inspection:
%dw 2.0
output application/json
---
{
payloadType: typeOf(payload),
isArray: payload is Array,
isObject: payload is Object,
keys: if (payload is Object) keysOf(payload) else null,
size: sizeOf(payload default [])
}Quick Reference: Common Fixes
| Error | Quick Fix |
|-------|-----------|
| Cannot coerce null | Add default value |
| Cannot coerce string to number | Use as Number default 0 |
| Unable to parse JSON | Use read(payload, "application/json") |
| Heap space | Add streaming=true or deferred=true |
| Duplicate key | Use -- to remove before merge |
| Index out of bounds | Use [n] default null |
| Date parse error | Use explicit format pattern |
| Encoding error | Set encoding="UTF-8" |
Complex DataWeave Transformations?
DataWeave mastery takes time. Our team can help with:
- Complex transformation development
- Performance optimization
- Custom module creation
- Migration from other ETL tools