Trieda ErrorException

Trieda ErrorException dedí od základnej triedy Exception a používa sa na transformáciu chýb PHP na výnimky. Pridáva ku štandardnej funkcionalite výnimiek informáciu o závažnosti chyby (severity). Trieda je obzvlášť užitočná pri použití s funkciou set_error_handler.

Syntax

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

Príklad

Vytvorme a spracujme ErrorException:

php<?php
  try {
    throw new ErrorException('Critical error', 0, E_ERROR);
  } catch (ErrorException $e) {
    echo 'Error: ' . $e->getMessage();
    echo ' Severity: ' . $e->getSeverity();
  }
?>

Výsledok vykonania kódu:

php'Error: Critical error Severity: 1'

Príklad

Transformujme štandardné chyby PHP na výnimky:

php<?php
  function errorHandler($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
  }
  
  set_error_handler('errorHandler');
  
  try {
    strpos(); // Nesprávny počet argumentov
  } catch (ErrorException $e) {
    echo 'Caught exception: ' . $e->getMessage();
    echo ' in ' . $e->getFile();
    echo ' on line ' . $e->getLine();
  }
?>

Výsledok vykonania kódu (príklad):

php'Caught exception: strpos() expects at least 2 parameters, 0 given in /path/to/file.php on line 10'

Príklad

Získajme informáciu o závažnosti chyby:

php<?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');
  }
?>

Výsledok vykonania kódu:

php'Severity level: 2 Is warning: yes'

Pozri tiež

  • trieda Exception,
    základná trieda pre všetky výnimky v PHP
  • funkciu set_error_handler,
    ktorá nastavuje užívateľský handler chýb