Klass ErrorException

Klass ErrorException pärineb baasklassist Exception ja seda kasutatakse PHP vigade teisendamiseks eranditeks. See lisab standardsele erandite funktsionaalsusele vea tõsiduse (severity) teabe. Klass on eriti kasulik funktsiooniga set_error_handler kasutamisel.

Süntaks

phpnew ErrorException(
  string $message = "",
  int $code = 0,
  int $severity = E_ERROR,
  string $filename = __FILE__,
  int $lineno = __LINE__,
  Throwable $previous = null
);

Näide

Loome ja töötleme ErrorExceptionit:

php<?php
  try {
    throw new ErrorException('Kriitiline viga', 0, E_ERROR);
  } catch (ErrorException $e) {
    echo 'Viga: ' . $e->getMessage();
    echo ' Tõsidus: ' . $e->getSeverity();
  }
?>

Koodi täitmise tulemus:

php'Viga: Kriitiline viga Tõsidus: 1'

Näide

Teisendame standardseid PHP vigu eranditeks:

php<?php
  function errorHandler($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
  }
  
  set_error_handler('errorHandler');
  
  try {
    strpos(); // Vale argumentide arv
  } catch (ErrorException $e) {
    echo 'Püütud erand: ' . $e->getMessage();
    echo ' failis ' . $e->getFile();
    echo ' real ' . $e->getLine();
  }
?>

Koodi täitmise tulemus (näide):

php'Püütud erand: strpos() expects at least 2 parameters, 0 given in /path/to/file.php on line 10'

Näide

Saame teabe vea tõsidusastme kohta:

php<?php
  try {
    throw new ErrorException('Hoiatussõnum', 0, E_WARNING);
  } catch (ErrorException $e) {
    echo 'Tõsidusaste: ' . $e->getSeverity();
    echo ' Kas hoiatus: ' . ($e->getSeverity() === E_WARNING ? 'jah' : 'ei');
  }
?>

Koodi täitmise tulemus:

php'Tõsidusaste: 2 Kas hoiatus: jah'

Vaata ka