Custom Exceptions
Extend Exception (or any descendant) to create domain-specific exceptions with extra context, enabling precise catch blocks in calling code.
Extend Exception (or any descendant) to create domain-specific exceptions with extra context, enabling precise catch blocks in calling code.
<?php
// Base domain exception
class AppException extends RuntimeException {}
// Specific exceptions
class NotFoundException extends AppException {
public function __construct(string $resource, int $id) {
parent::__construct("{$resource} with ID {$id} not found", 404);
}
}
class ValidationException extends AppException {
public function __construct(private array $errors) {
parent::__construct("Validation failed", 422);
}
public function getErrors(): array {
return $this->errors;
}
}
// Usage
throw new NotFoundException("User", 42);
throw new ValidationException(["email" => "Email is required"]);
Create a hierarchy of custom exceptions rooted at a single AppException — catch AppException to handle all domain errors in one place.