Creating Custom Exceptions
Extend the Exception class to build domain-specific error types.
Why Custom Exceptions?
Custom exceptions let you:
- Distinguish your application errors from generic PHP errors
- Carry domain-specific data (order ID, user ID, etc.)
- Catch specific error types at different layers
- Create meaningful, self-documenting error hierarchies
Extending Exception
Create a custom exception by extending the Exception base class:
<?php
class ValidationException extends \Exception
{
private array $errors;
public function __construct(array $errors, string $message = '', int $code = 0)
{
$this->errors = $errors;
parent::__construct($message ?: implode(', ', $errors), $code);
}
public function getErrors(): array
{
return $this->errors;
}
}All lessons in this course
- PHP Error Types and Reporting
- Try, Catch, and Finally
- Creating Custom Exceptions
- Logging Errors and Best Practices