Data Transform With Row Level Error Context

A record transformer that keeps row indices and source values in every error, so a failing batch traces back to the exact offending record.

JavascriptData Integrity

Code

export class TransformError extends Error {
  constructor(message, details) {
    super(message);
    this.name = "TransformError";
    this.index = details.index;
    this.key = details.key ?? null;
    this.raw = details.raw;
  }
}

export async function transformRecords(records, transform, options = {}) {
  const keyField = options.keyField ?? "id";
  if (!Array.isArray(records)) {
    throw new TypeError("records must be an array");
  }
  const out = [];
  for (let index = 0; index < records.length; index++) {
    const raw = records[index];
    if (!raw || typeof raw !== "object") {
      throw new TransformError("record at index " + index + " is not an object", {
        index,
        key: null,
        raw,
      });
    }
    let value;
    try {
      value = await transform(raw, index);
    } catch (err) {
      throw new TransformError(
        "transform failed at index " + index + ": " + String(err.message ?? err),
        { index, key: raw[keyField] ?? null, raw },
      );
    }
    if (value === undefined) {
      throw new TransformError("transform returned undefined at index " + index, {
        index,
        key: raw[keyField] ?? null,
        raw,
      });
    }
    out.push(value);
  }
  return out;
}

A map over records throws a bare error, so nobody knows which of ten thousand rows was malformed or what its raw value was.

Use case: engineers transforming imported data where one bad row must not lose its address

Inputs / outputs

  • Input: an array of raw records plus a per-record transform function
  • Output: transformed records, or an error carrying row index, key and raw value

Error conditions

  • transform throws for a record
  • record is null or not an object
  • transform returns undefined

Approach

iterate with index; wrap each transform in try/catch; on failure rethrow a TransformError decorated with index, key and the raw record.

Implementation

export class TransformError extends Error {
  constructor(message, details) {
    super(message);
    this.name = "TransformError";
    this.index = details.index;
    this.key = details.key ?? null;
    this.raw = details.raw;
  }
}

export async function transformRecords(records, transform, options = {}) {
  const keyField = options.keyField ?? "id";
  if (!Array.isArray(records)) {
    throw new TypeError("records must be an array");
  }
  const out = [];
  for (let index = 0; index < records.length; index++) {
    const raw = records[index];
    if (!raw || typeof raw !== "object") {
      throw new TransformError("record at index " + index + " is not an object", {
        index,
        key: null,
        raw,
      });
    }
    let value;
    try {
      value = await transform(raw, index);
    } catch (err) {
      throw new TransformError(
        "transform failed at index " + index + ": " + String(err.message ?? err),
        { index, key: raw[keyField] ?? null, raw },
      );
    }
    if (value === undefined) {
      throw new TransformError("transform returned undefined at index " + index, {
        index,
        key: raw[keyField] ?? null,
        raw,
      });
    }
    out.push(value);
  }
  return out;
}

Verification tests

import { test } from "node:test";
import assert from "node:assert/strict";
import { TransformError, transformRecords } from "./example.mjs";

test("passes valid records through", async () => {
  const out = await transformRecords([{ id: "a", n: 1 }, { id: "b", n: 2 }], (r) => ({ id: r.id, n: r.n * 10 }));
  assert.deepEqual(out, [{ id: "a", n: 10 }, { id: "b", n: 20 }]);
});

test("decorates a transform failure with row context", async () => {
  const records = [{ id: "ok", n: 1 }, { id: "bad", n: "x" }];
  await assert.rejects(
    async () =>
      transformRecords(records, (r) => {
        if (typeof r.n !== "number") throw new TypeError("n must be a number");
        return { id: r.id, n: r.n * 2 };
      }),
    (err) => {
      assert.ok(err instanceof TransformError);
      assert.equal(err.index, 1);
      assert.equal(err.key, "bad");
      assert.deepEqual(err.raw, { id: "bad", n: "x" });
      return true;
    },
  );
});

test("rejects records that are not objects", async () => {
  await assert.rejects(
    async () => transformRecords([null], (r) => r),
    (err) => err instanceof TransformError && err.index === 0,
  );
});

test("rejects a transform returning undefined", async () => {
  await assert.rejects(
    async () => transformRecords([{ id: "a" }], () => undefined),
    /returned undefined at index 0/,
  );
});

Dependencies and running

No external dependencies (standard library only).

Runtime: node >= 18 Entry point: node example.mjs

Limitations and error handling

single pass only; no partial-result mode; no automatic retry per row.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic