ErrorException
PHPERRORCommonError Handling

PHP error converted to a catchable exception

Quick Answer

Install a set_error_handler that throws ErrorException to treat PHP warnings as catchable exceptions.

What this means

A standard exception that wraps a PHP E_* error. Use set_error_handler to convert all errors into ErrorExceptions so they can be caught with try-catch.

Why it happens
  1. 1E_WARNING from file_get_contents on a missing URL
  2. 2E_NOTICE from accessing an undefined array key

Fix

Global error-to-exception converter

Global error-to-exception converter
set_error_handler(function (int $severity, string $msg, string $file, int $line): bool {
    if (!(error_reporting() & $severity)) return false;
    throw new \ErrorException($msg, 0, $severity, $file, $line);
});

Why this works

set_error_handler intercepts E_* errors; throwing ErrorException makes them catchable.

Code examples
Catch file warningphp
try {
    $data = file_get_contents($url);
} catch (\ErrorException $e) {
    $data = null;
    log_error($e->getMessage());
}
getSeverity()php
catch (\ErrorException $e) {
    if ($e->getSeverity() === E_WARNING) { /* handle */ }
}
Same error in other languages

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PHP errors