{"record":{"id":"c5779c5aed670403","repo":"briannesbitt/Carbon","slug":"unable-to-add-unit-var-export-originalargs-tru","errorCode":null,"errorMessage":"Unable to add unit '.var_export($originalArgs, true)","messagePattern":"Unable to add unit '\\.var_export\\(\\$originalArgs, true\\)","errorType":"exception","errorClass":"UnitException","httpStatus":null,"severity":"error","filePath":"src/Carbon/Traits/Units.php","lineNumber":394,"sourceCode":"            $date = self::rawAddUnit($date, $unit, $value);\n\n            if ($date !== null) {\n                if (isset($timeString)) {\n                    $date = $date->setTimeFromTimeString($timeString);\n                } elseif (isset($canOverflow, $day) && $canOverflow && $day !== $date->day) {\n                    $date = $date->modify('last day of previous month');\n                }\n\n                if ($anchorDay !== null) {\n                    $date = $date->setAnchorDay($anchorDay);\n                }\n            }\n        } catch (DateMalformedStringException|InvalidFormatException|UnsupportedUnitException $exception) {\n            $date = null;\n            $previousException = $exception;\n        }\n\n        return $date ?? throw new UnitException(\n            'Unable to add unit '.var_export($originalArgs, true),\n            previous: $previousException,\n        );\n    }\n\n    /**\n     * Subtract given units to the current instance.\n     */\n    public function subUnit(\n        Unit|string $unit,\n        $value = 1,\n        OverflowMode|bool|null $overflow = null,\n        ?int $anchorDay = null,\n    ): static {\n        return $this->addUnit($unit, -$value, $overflow, $anchorDay);\n    }\n\n    /**","sourceCodeStart":376,"sourceCodeEnd":412,"githubUrl":"https://github.com/briannesbitt/Carbon/blob/b13f05955dcfd7da71d60af745fd148cbdb73505/src/Carbon/Traits/Units.php#L376-L412","documentation":"addUnit() (also reachable via add()/subUnit()/subtract()) converts the unit and value to a CarbonInterval or falls back to DateTime::modify inside rawAddUnit(); if that pipeline throws UnsupportedUnitException, DateMalformedStringException or InvalidFormatException, the date result is null and Carbon rethrows UnitException with var_export() of the original arguments and the root cause chained as previous. It is the catch-all 'the unit/value pair could not be applied' error, so the real reason is in getPrevious().","triggerScenarios":"$date->addUnit('fortnight', 3) where neither CarbonInterval::fromString('3 fortnight') nor modify('3 fortnight') parses; $date->add(5, 'dayz') typo; a string value like 'NaN' or INF surviving is_numeric guards in float form and producing a malformed modify string; huge computed values (e.g. 1e17 years) that overflow PHP's date range during the fallback modify.","commonSituations":"Unit typos in migrated code; unit enums/strings from external input passed unvalidated; arithmetic on user-supplied quantities producing astronomically large values; Carbon major upgrades where a previously tolerated unit string is no longer parsed by the interval parser.","solutions":["Inspect getPrevious() on the caught UnitException: UnsupportedUnitException means the unit is unrecognized, DateMalformedStringException/InvalidFormatException points at the value/string","Fix or whitelist the unit against the Unit enum / supported list before calling addUnit","Clamp or bound computed values (reject |value| beyond a sane range) before passing them in","Catch UnitException at the boundary and map it to a 422/validation error instead of a 500"],"exampleFix":"// before\n$date->addUnit($unitFromRequest, $amount);\n\n// after\ntry {\n    $date->addUnit($unitFromRequest, $amount);\n} catch (UnitException $e) {\n    $reason = $e->getPrevious() ? get_class($e->getPrevious()) : 'unknown';\n    throw new InvalidArgumentException(\"Cannot apply $amount $unitFromRequest ($reason)\", 0, $e);\n}","handlingStrategy":"try-catch","validationCode":"$value = (float) $amount;\nif (!is_finite($value) || abs($value) > 1e9) {\n    throw new InvalidArgumentException(\"Refusing to add unrealistic amount: $amount\");\n}\nif (!$unit instanceof Unit && !in_array((string) $unit, array_map(fn (Unit $u) => $u->value, Unit::cases()), true)) {\n    throw new InvalidArgumentException(\"Unknown unit: $unit\");\n}","typeGuard":"function isKnownUnit(mixed $unit): bool\n{\n    if ($unit instanceof Unit) {\n        return true;\n    }\n    static $names;\n    $names ??= array_map(fn (Unit $u) => $u->value, Unit::cases());\n\n    return in_array(Carbon::singularUnit(strtolower((string) $unit)), $names, true);\n}","tryCatchPattern":"use Carbon\\Exceptions\\UnitException;\n\ntry {\n    $result = $date->addUnit($unit, $value);\n} catch (UnitException $e) {\n    $root = $e->getPrevious(); // UnsupportedUnitException | InvalidFormatException | DateMalformedStringException\n    logger()->warning('addUnit failed', ['unit' => $unit, 'value' => $value, 'root' => $root]);\n    throw new ValidationException('Unsupported date arithmetic');\n}","preventionTips":["Always inspect getPrevious() - the outer UnitException hides the real cause","Bound user-supplied magnitudes before date arithmetic; PHP date range is year 1-9999","Centralize unit validation with the Unit enum at your input layer"],"tags":["php","carbon","date-arithmetic","unit-validation","exception-chaining"],"backgroundTag":"date-arithmetic-failed","analyzedSha":"b13f05955dcfd7da71d60af745fd148cbdb73505","analyzedAt":"2026-08-17T04:40:56.953Z","schemaVersion":2},"datasetVersion":"2026-08-17T09:17:11.063Z"}