Classe ErrorException
La classe ErrorException eredita dalla classe base Exception e viene utilizzata
per convertire gli errori PHP in eccezioni. Aggiunge alla funzionalità standard
delle eccezioni informazioni sulla gravità dell'errore (severity). La classe è particolarmente utile
quando utilizzata con la funzione set_error_handler.
Sintassi
new ErrorException(
string $message = "",
int $code = 0,
int $severity = E_ERROR,
string $filename = __FILE__,
int $lineno = __LINE__,
Throwable $previous = null
);
Esempio
Creiamo e gestiamo un ErrorException:
<?php
try {
throw new ErrorException('Critical error', 0, E_ERROR);
} catch (ErrorException $e) {
echo 'Error: ' . $e->getMessage();
echo ' Severity: ' . $e->getSeverity();
}
?>
Risultato dell'esecuzione del codice:
'Error: Critical error Severity: 1'
Esempio
Convertiamo gli errori standard di PHP in eccezioni:
<?php
function errorHandler($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler('errorHandler');
try {
strpos(); // Numero errato di argomenti
} catch (ErrorException $e) {
echo 'Caught exception: ' . $e->getMessage();
echo ' in ' . $e->getFile();
echo ' on line ' . $e->getLine();
}
?>
Risultato dell'esecuzione del codice (esempio):
'Caught exception: strpos() expects at least 2 parameters, 0 given in /path/to/file.php on line 10'
Esempio
Otteniamo informazioni sulla gravità dell'errore:
<?php
try {
throw new ErrorException('Warning message', 0, E_WARNING);
} catch (ErrorException $e) {
echo 'Severity level: ' . $e->getSeverity();
echo ' Is warning: ' . ($e->getSeverity() === E_WARNING ? 'yes' : 'no');
}
?>
Risultato dell'esecuzione del codice:
'Severity level: 2 Is warning: yes'
Vedi anche
-
classe
Exception,
classe base per tutte le eccezioni in PHP -
funzione
set_error_handler,
che imposta un gestore di errori personalizzato