Proper error handling is crucial for building robust PHP applications. PHP offers several mechanisms to handle errors and exceptions gracefully.
Error Reporting Configuration
// Development environment
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Production environment
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/php-errors.log');
Exception Handling
PHP uses try-catch blocks for exception handling:
try {
$file = fopen("nonexistent.txt", "r");
} catch (Throwable $e) {
error_log("File error: " . $e->getMessage());
echo "An error occurred. Please try again later.";
}
Custom Exception Classes
class ValidationException extends InvalidArgumentException {
public function __construct(
public readonly array $errors,
string $message = "Validation failed"
) {
parent::__construct($message);
}
}
try {
throw new ValidationException(['email' => 'Invalid format']);
} catch (ValidationException $e) {
foreach ($e->errors as $field => $error) {
echo "$field: $error\n";
}
}
Error Handling Best Practices
- Log all errors in production
- Create custom exception classes for domain-specific errors
- Use finally blocks for cleanup operations
- Implement a global exception handler
- Convert errors to exceptions with set_error_handler()
Global Exception Handler
set_exception_handler(function (Throwable $e) {
error_log("Uncaught exception: " . $e->getMessage());
http_response_code(500);
if (ENVIRONMENT === 'development') {
echo "Error: " . $e->getMessage();
} else {
echo "An unexpected error occurred";
}
});
Implementing these error handling strategies will make your application more reliable and easier to debug.
