Типы ошибок PHP
Классификация ошибок
| Константа | Значение | Описание | Фатальная? |
|---|---|---|---|
E_ERROR |
1 | Фатальная ошибка | Да |
E_WARNING |
2 | Предупреждение | Нет |
E_PARSE |
4 | Ошибка парсинга | Да |
E_NOTICE |
8 | Уведомление | Нет |
E_CORE_ERROR |
16 | Ошибка ядра PHP | Да |
E_CORE_WARNING |
32 | Предупреждение ядра | Нет |
E_COMPILE_ERROR |
64 | Ошибка компиляции | Да |
E_COMPILE_WARNING |
128 | Предупреждение компиляции | Нет |
E_USER_ERROR |
256 | Пользовательская ошибка | Да |
E_USER_WARNING |
512 | Пользовательское предупреждение | Нет |
E_USER_NOTICE |
1024 | Пользовательское уведомление | Нет |
E_STRICT |
2048 | Рекомендации | Нет |
E_RECOVERABLE_ERROR |
4096 | Перехватываемая фатальная | Условно |
E_DEPRECATED |
8192 | Устаревший код | Нет |
E_USER_DEPRECATED |
16384 | Пользовательское deprecated | Нет |
E_ALL |
32767 | Все ошибки | - |
<?php
declare(strict_types=1);
// E_NOTICE — undefined variable (PHP 8.0+: E_WARNING)
// echo $undefinedVar; // Warning: Undefined variable
// E_WARNING — non-fatal
// $result = file_get_contents('nonexistent.txt'); // Warning: failed to open
// E_ERROR — fatal, stops execution
// nonExistentFunction(); // Fatal error: Call to undefined function
// E_DEPRECATED — deprecated feature
// $result = strstr('test', ''); // Deprecated in PHP 8.3
error_reporting
<?php
declare(strict_types=1);
// Set which errors to report
error_reporting(E_ALL); // All errors
error_reporting(E_ALL & ~E_NOTICE); // All except notices
error_reporting(E_ALL & ~E_DEPRECATED); // All except deprecated
error_reporting(E_ERROR | E_WARNING); // Only errors and warnings
error_reporting(0); // No reporting
// Get current level
$level = error_reporting();
// Bitwise operations for error levels:
// & — AND (keep common bits)
// | — OR (combine bits)
// ~ — NOT (invert bits)
// ^ — XOR (toggle bits)
// Common configurations:
// Development:
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
// Production:
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', '/var/log/php/error.log');
Запомни: В продакшене:
display_errors = Off,log_errors = On. В разработке:display_errors = On,error_reporting = E_ALL. Никогда не показывайте ошибки пользователям в продакшене — это утечка информации.
Пользовательские обработчики ошибок
<?php
declare(strict_types=1);
// Custom error handler
set_error_handler(function (
int $errno,
string $errstr,
string $errfile,
int $errline,
): bool {
// Convert errors to exceptions
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
// Now warnings become exceptions
try {
$result = 1 / 0; // DivisionByZeroError in PHP 8.0+
} catch (Throwable $e) {
echo "Caught: {$e->getMessage()}";
}
// Restore default handler
restore_error_handler();
// Custom shutdown handler (catches fatal errors)
register_shutdown_function(function (): void {
$error = error_get_last();
if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR], true)) {
error_log("Fatal: {$error['message']} in {$error['file']}:{$error['line']}");
}
});
Ловушка экзамена:
set_error_handler()НЕ перехватываетE_ERROR,E_PARSE,E_CORE_ERROR,E_CORE_WARNING,E_COMPILE_ERROR,E_COMPILE_WARNING. Для перехвата фатальных ошибок используйтеregister_shutdown_function()+error_get_last().
trigger_error
<?php
declare(strict_types=1);
// Trigger user-level errors
function divide(float $a, float $b): float
{
if ($b == 0.0) {
trigger_error('Division by zero', E_USER_WARNING);
return 0.0;
}
return $a / $b;
}
// E_USER_ERROR — fatal (deprecated, use exceptions instead)
// E_USER_WARNING — warning
// E_USER_NOTICE — notice
// E_USER_DEPRECATED — deprecated feature
trigger_error('This function is deprecated, use newFunc()', E_USER_DEPRECATED);
Изменения в PHP 8.0+
<?php
declare(strict_types=1);
// PHP 8.0: Many warnings became errors/exceptions
// Before PHP 8.0: E_WARNING -> Now: TypeError
// strlen(null); // TypeError
// Before PHP 8.0: E_NOTICE -> Now: E_WARNING
// $arr = []; echo $arr[0]; // Warning: Undefined array key
// Before PHP 8.0: @ silenced all -> Now: doesn't silence fatal
// @undefinedFunction(); // Still throws Error
// Division by zero: DivisionByZeroError (not E_WARNING anymore)
try {
$result = 1 / 0; // DivisionByZeroError
} catch (DivisionByZeroError $e) {
echo $e->getMessage();
}