InvalidArgumentException
PHPERRORCommonValidation
Function argument is invalid
Quick Answer
Throw InvalidArgumentException at function entry when argument values violate preconditions.
What this means
SPL exception for invalid arguments — the argument type may be correct but fails domain validation. Throw this in your own functions to signal bad input.
Why it happens
- 1Negative page size passed to a paginator
- 2Empty string where a non-empty value is required
Fix
Guard at entry
Guard at entry
function paginate(array $items, int $perPage): array {
if ($perPage < 1) {
throw new \InvalidArgumentException("perPage must be >= 1, got $perPage");
}
return array_chunk($items, $perPage);
}Why this works
Failing fast with a descriptive message makes the call site obvious in stack traces.
Code examples
Throw on bad inputphp
if (!in_array($status, ['active','inactive'])) {
throw new \InvalidArgumentException("Unknown status: $status");
}Catch in controllerphp
try {
$pages = paginate($items, $request->perPage);
} catch (\InvalidArgumentException $e) {
return response()->json(['error' => $e->getMessage()], 422);
}Same error in other languages
Sources
Official documentation ↗
PHP Manual
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev