dotnet/eShop · error · OrderingDomainException

Invalid units

Error message

Invalid units

What it means

Thrown by OrderItem.AddUnits when the supplied units argument is less than zero. AddUnits is meant to increment an existing line's quantity; a negative argument would silently decrement (or underflow) the line, so it is rejected as a domain invariant violation. It is an OrderingDomainException.

Source

Thrown at src/Ordering.Domain/AggregatesModel/OrderAggregate/OrderItem.cs:58

        Units = units;
        PictureUrl = pictureUrl;
    }
    
    public void SetNewDiscount(decimal discount)
    {
        if (discount < 0)
        {
            throw new OrderingDomainException("Discount is not valid");
        }

        Discount = discount;
    }

    public void AddUnits(int units)
    {
        if (units < 0)
        {
            throw new OrderingDomainException("Invalid units");
        }

        Units += units;
    }
}

View on GitHub (pinned to 9b4f9434f4)

Solutions

  1. Validate the delta is non-negative at the call site before AddUnits; route decreases through a separate decrement/remove-line path.
  2. Fix the delta computation: if (newQty > oldQty) item.AddUnits(newQty - oldQty) else item.Remove/adjust via the appropriate method.
  3. Add a handler-level guard: if (units < 0) reject the request.
  4. Unit-test AddUnits with a negative argument to lock in the throw behavior.

Example fix

// before
item.AddUnits(newQty - oldQty); // negative when decreasing

// after
var delta = newQty - oldQty;
if (delta > 0) item.AddUnits(delta);
else if (delta < 0) /* use the remove/adjust path */;
Defensive patterns

Strategy: validation

Validate before calling

if (units < 0) throw new ArgumentOutOfRangeException(nameof(units));
item.AddUnits(units);

Type guard

static bool IsValidDelta(int units) => units >= 0;

Try / catch

try {
    item.AddUnits(delta);
} catch (OrderingDomainException ex) when (ex.Message == "Invalid units") {
    // negative delta — route through the decrement/remove path instead
}

Prevention

When it happens

Trigger: Calling existingOrderForProduct.AddUnits(units) (via Order.AddOrderItem for an already-present product, or directly) with a negative delta. Arises from sign errors when merging duplicate lines, or from passing a delta computed as (newQty - oldQty) where newQty < oldQty.

Common situations: Client intent to update quantity downward routed through AddUnits instead of a dedicated remove path; merge logic subtracting and forwarding the negative remainder; a stale request replaying an old negative delta.

Related errors


AI-assisted analysis of dotnet/eShop@9b4f9434f4 (2026-08-13). Data as JSON: /api/errors/706bee81ce17572f. Report an issue: GitHub.