DomainException
PHPERRORCommonLogic
Value does not adhere to a valid data domain
Quick Answer
Throw DomainException for domain model invariant violations — e.g., an order total that is negative.
What this means
Logic exception indicating a value does not adhere to a defined valid data domain. Used for invariant violations that represent programming errors.
Why it happens
- 1Negative price set on a product
- 2Invalid state transition in a state machine
Fix
Enforce domain invariant
Enforce domain invariant
class Money {
public function __construct(private int $amount, private string $currency) {
if ($amount < 0) {
throw new \DomainException("Amount cannot be negative: $amount");
}
}
}Why this works
Constructor invariant check prevents invalid domain objects from ever being created.
Code examples
State machine guardphp
if (!in_array($newState, $this->validTransitions[$this->state])) {
throw new \DomainException("Cannot transition from {$this->state} to $newState");
}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