Error handling
Every exception the package throws implements Dirthara\Validation\Exception\ValidationException. Catch that interface
to handle anything from the package, or a specific exception to handle one failure. Each exception carries a context
array with the details of the failure, and addContext() adds to it.
| Exception | Extends | Thrown when |
|---|---|---|
InvalidRuleException | InvalidArgumentException | A validator or rule is configured with something invalid. |
ValidationFailedException | RuntimeException | You throw it for a failed result. |
Invalid rules
ValidatorFactory::create() and Each throw InvalidRuleException for an entry that is not a rule. Its context holds
the entry as rule, and the factory adds the field as field.
try {
$factory->create(['email' => [new Email(), 'required']]);
} catch (InvalidRuleException $exception) {
$exception->getMessage(); // 'Rule "string" is not a valid rule.'
$exception->context; // ['rule' => 'required', 'field' => 'email']
}
The factory also rejects integer field keys during construction with InvalidRuleException; its context contains
field. PHP converts numeric string keys such as '0' to integers, so those keys are rejected too. Collection indexes
inside Each remain valid integers.
Rules that take arguments check them when they are created:
| Rule | Throws when | Context |
|---|---|---|
Regex | The pattern is not a valid regular expression. | pattern |
Between | The minimum is greater than the maximum. | minimum, maximum |
Length, MinLength, MaxLength | The configured size is negative. | rule, parameter, value |
Count, MinCount, MaxCount | The configured count is negative. | rule, parameter, value |
RequiredWithAll, RequiredWithoutAll | The reference list is empty. | rule |
RequiredWithAll, RequiredWithoutAll | A reference is not a string. | rule, fieldType |
For size and reference errors, rule is the rule class name. parameter names the size argument, and value is its
configured value. fieldType describes the invalid reference type. Zero lengths and counts are valid.
Failed validation
Validation itself never throws for invalid input; it returns a result. When you would rather stop with an exception, create one from the result:
$result = $validator->validate($input);
if ($result->failed()) {
throw ValidationFailedException::forResult($result);
}
The exception keeps the whole result in result. Its message and its fields context name the fields that failed.
The message and the context never contain the input values, because an exception ends up in logs and error trackers. Read the values from your input, not from the exception.