How Lodash partition Handles Callback Exceptions

In the Lodash JavaScript library, _.partition splits a collection into two distinct arrays based on the truth value returned by an iteratee predicate. If this predicate callback throws an exception halfway through processing, Lodash does not catch, swallow, or suppress the error. The execution immediately halts, any partial progress is lost without returning an incomplete result, and the exception bubbles directly up the call stack to the surrounding execution context.

Immediate Execution Halt

Lodash functions rely on standard synchronous JavaScript control flow. Internally, _.partition iterates through the collection sequentially using an aggregator function. It does not wrap calls to the iteratee in a try...catch block.

When the callback throws an error on a specific element:

  1. Loop Termination: Iteration stops immediately at the offending element.
  2. Remaining Elements Ignored: Elements in the collection after the failing element are never evaluated or passed to the callback.
  3. No Return Value: The function does not return an array containing partially partitioned data. The references to the internal accumulators are dropped.
  4. Error Propagation: The unhandled error must be caught by a try...catch block in your code; otherwise, it results in an unhandled exception that can crash the running Node.js process or trigger an onerror event in the browser.

State and Side Effects

Because _.partition is a non-mutating utility, the original collection remains intact and unmodified even when an exception is thrown midway. However, if the custom predicate modified external variables or mutated elements before the failure occurred, those side effects will persist.

Safe Error-Handling Patterns

To handle collections where predicate evaluations may fail without interrupting the entire partitioning process, you must handle exceptions within the callback itself or wrap the outer execution.

Handling Errors Inside the Iteratee

If you want processing to continue despite errors, handle the failure directly within the predicate so it returns a boolean fallback:

const _ = require('lodash');

const data = [1, 2, 'invalid', 4];

const [evens, others] = _.partition(data, (item) => {
  try {
    if (typeof item !== 'number') {
      throw new Error(`Invalid item: ${item}`);
    }
    return item % 2 === 0;
  } catch (error) {
    // Decide whether failed items belong in the truthy or falsy partition
    return false;
  }
});

Catching Errors at the Call Site

If an exception indicates an unrecoverable state where the entire operation should be aborted, wrap the _.partition call:

try {
  const [valid, invalid] = _.partition(collection, riskyPredicate);
} catch (error) {
  console.error('Partitioning aborted due to an error:', error);
}