D365FO Data Entities SCD: how to capture field-level details when `validateWrite`/`write` fails in X++ preprocessing
In D365FO Data Entities that use SCD (extended data entities / data entities with staging + SCD mapping to EDT-backed fields), validateWrite or write can fail with an error message that doesn’t clearly identify the source field or stack.
What are the practical techniques to intercept and diagnose these failures during X++ pre-processing—e.g., how to log/collect field-level errors, record the staging/entity buffer state, and distinguish whether the failure comes from:
- entity mapping/EDT conversion,
- staging validations,
- SCD processing/table constraints—especially when the exception surfaces only from
validateWrite()/write()?
Please include example X++ patterns (event handlers or overriding extensions) for capturing the failing record/field(s) and correlating it back to the incoming payload/field mapping.
1 answer
Write an answerWhat you’re trying to do#
During Data Entity preprocessing you want to identify exactly which incoming field / mapped EDT field caused an SCD write/validate failure, even though the exception/error only surfaces when the framework calls validateWrite() / write().
In SCD scenarios (Staging + mapping + history/versioning), the real failure can come from different layers (conversion/mapping, staging validation, or the SCD target/history tables + constraints). The framework often only throws a generic write/validate error unless you intercept earlier/lower in the pipeline.
The key point: preprocess is “too early” for some errors#
If you only hook preprocess (for example, preProcessRecord) you can log what you sent, but the framework will still later call staging/SCD write logic. At that later point, you need context captured during preprocess (payload + staging buffer values + mapping candidates), and then capture the failure at the moment validateWrite()/write() is executed.
Practically, you do this with two kinds of interception:
- capture context in preprocess (store a correlation key and all staging/EDT candidate values),
- capture the exception details when the framework fails to write (via Data Entity event handlers or an exception handler that can access record context).
Technique A (recommended): capture a correlation key + buffer snapshot in preprocess#
In preprocessing you can:
- log the incoming entity payload values (or the staging buffer equivalent),
- compute a correlation key (e.g., business keys + a hash of payload fields),
- store those values in a temp table / log table (or in-memory if the run is single-threaded).
Why: when validateWrite()/write() fails later, you often only have access to “current record” buffers. With a correlation key you can map that buffer back to the payload you stored earlier.
Example pattern: preprocess capture (event handler)#
[DataEntityPreProcessRecord(tableStr(MyStagingTable), true)]
public static void preProcessRecCommon(
MyEntityPreProcessRecordContext _context)
{
MyStagingTable stg = _context.getRecord();
// Build a correlation key (use your entity’s business key fields)
// Hashing payload is optional; even BK values is often enough.
str corr = strFmt(
"%1|%2|%3",
stg.MyBusinessKey1,
stg.MyBusinessKey2,
stg.MyBusinessKeyDate);
// Store correlation + the candidate fields you expect to be validated
// (Do NOT rely only on what you see in the exception; capture everything now.)
MyDeErrorCapture tmp;
tmp.clear();
tmp.CorrelationKey = corr;
tmp.StagingRecId = stg.RecId;
tmp.Field1 = stg.MyField1;
tmp.Field2 = stg.MyField2;
tmp.RawPayloadJson = _context.getOriginalPayload(); // if available in your context
tmp.insert();
}Notes
- The exact event signature types differ by entity generator version; the pattern is: extract staging record values in preprocess and persist them with a correlation key.
- If your preprocess context can’t provide original payload JSON, still capture all staging fields you suspect.
Technique B: catch the exception at the framework write boundary#
To distinguish where the error came from, you want to capture:
- the exact exception message (and inner exception text if any),
- the record identity/context currently being written,
- any additional error details the framework attaches.
In many Data Entity implementations, you can use a Data Entity exception event (or a wrapper around write) to intercept when the framework fails the record.
Example pattern: Data Entity error handler that logs message + correlation key#
[DataEntityErrorHandler(tableStr(MyStagingTable))]
public static void onDeError(
DataEntityErrorHandlerContext _ctx)
{
MyStagingTable stg = _ctx.getRecord();
str corr = strFmt(
"%1|%2|%3",
stg.MyBusinessKey1,
stg.MyBusinessKey2,
stg.MyBusinessKeyDate);
MyDeErrorCapture log;
log.selectForUpdate(false);
log = MyDeErrorCapture::findByCorrelationKey(corr);
MyDeErrorResult res;
res.clear();
res.CorrelationKey = corr;
res.StagingRecId = stg.RecId;
res.ErrorText = _ctx.getErrorMessage();
res.ErrorCode = _ctx.getErrorCode();
res.InnerErrorText = _ctx.getInnerErrorText();
res.insert();
}Why this helps
- The failing record will still exist as a staging record/buffer in most cases.
- With correlation key, you retrieve what was populated during preprocess.
Technique C: classify the failure source (conversion vs staging validation vs SCD constraints)#
You can usually classify without deep framework internals by what stage you observe and what message pattern you get.
1) Entity mapping / EDT conversion failures#
Symptoms:
- fail early (often before you can see a staging record with the final values),
- messages mention conversion, format, datatype, or EDT property issues (e.g., enums, extended data type validations).
What to do:
- In preprocess, log the incoming raw string/value and the parsed/assigned staging field.
- Also log the field-level “raw” candidates you get from the payload before assignment (if you can).
2) Staging validations#
Symptoms:
- staging record is created/updated,
- message references staging table constraints/validation, business rules, or “must be filled / range / pattern”.
What to do:
- Use pre-stage validation points if your entity provides them (or validate in preprocess) and log violations.
- In the error handler, capture staging field values and compare against rules.
3) SCD processing / table constraints#
Symptoms:
- staging validation may succeed,
- failure occurs specifically when SCD logic writes history/current rows (often uniqueness, effective date overlap, required SCD columns, versioning rules).
What to do:
- In preprocess, capture the effective-from / effective-to (or whatever your SCD mapping uses) plus business key fields.
- Log current+history candidate values (e.g., validFrom/validTo, status, partitioning keys).
Practical correlation strategy: record/field narrowing#
Even if the exception text doesn’t mention a field, you can still narrow down the culprit:
- Compute deltas: after preprocess, compare staging record fields you captured against a “known good” or against mandatory/range rules.
- Try-order your logging fields: capture high-risk fields first (date ranges, enums, strings with length/format, foreign key/relations).
- If your SCD mapping produces multiple target fields from one payload field, log the mapping inputs and all outputs.
Example: capture staging + SCD mapped “effective” columns explicitly#
// In preprocess capture include SCD effective columns too
tmp.EffectiveFrom = stg.ValidFrom;
tmp.EffectiveTo = stg.ValidTo;
tmp.ScdKey1 = stg.ScdKey1;
tmp.ScdKey2 = stg.ScdKey2;
// Also capture the raw incoming payload values you can
tmp.RawFieldX = _context.getFieldValueAsString('FieldX');Transaction + performance considerations#
- Don’t do heavy DB work per record in preprocess; write to a dedicated log table with minimal columns and batch where possible.
- If you insert log rows inside the same transaction as DE write, failures may roll back the log unless you manage transaction scope carefully.
- If you truly need logs even on rollback, use a pattern that writes in a separate transaction (but that’s implementation-specific—verify with your environment).
- Large payloads: avoid storing full JSON if it’s huge; store only fields you need.
Edge cases to account for#
- Cross-company: correlation key must include
dataAreaIdif SCD tables are company-specific. - Batch vs interactive: preprocessing/error events can behave differently; confirm your interceptors fire in your execution mode.
- Empty/null fields: conversion vs validation errors often hinge on nullability; log both “raw” (before conversion) and “assigned” (after conversion).
- Multiple records per payload: if your entity expands to multiple staging rows, correlation key must incorporate the row index or natural row identifier.
What you should implement first#
- Preprocess capture: store correlation key + candidate field values (including SCD effective columns).
- Write/validate error handler: capture exception text + record context and link back to correlation key.
- Classification logic: based on error message patterns + which fields were populated/changed.
This gives you actionable field-level diagnostics even when the framework only fails at validateWrite() / write().
Know the solution?
Sign in to contribute an answer and build your community reputation.
Sign in to answer