Klasa ErrorException

Klasa ErrorException trashëgon nga klasa bazë Exception dhe përdoret për shndërrimin e gabimeve të PHP-së në përjashtime. Ajo i shton funksionalitetit standard të përjashtimeve informacion rreth rëndësisë së gabimit (severity). Klasa është veçanërisht e dobishme gjatë përdorimit me funksionin set_error_handler.

Sintaksa

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

Shembull

Le të krijojmë dhe trajtojmë një ErrorException:

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

Rezultati i ekzekutimit të kodit:

php'Error: Critical error Severity: 1'

Shembull

Le të shndërrojmë gabimet standarde të PHP-së në përjashtime:

php<?php
  function errorHandler($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
  }
  
  set_error_handler('errorHandler');
  
  try {
    strpos(); // Numër i gabuar i argumenteve
  } catch (ErrorException $e) {
    echo 'Caught exception: ' . $e->getMessage();
    echo ' in ' . $e->getFile();
    echo ' on line ' . $e->getLine();
  }
?>

Rezultati i ekzekutimit të kodit (shembull):

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

Shembull

Le të marrim informacion rreth rëndësisë së gabimit:

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

Rezultati i ekzekutimit të kodit:

php'Severity level: 2 Is warning: yes'

Shihni gjithashtu

  • klasa Exception,
    klasa bazë për të gjitha përjashtimet në PHP
  • funksionin set_error_handler,
    i cili vendos një trajtesë të personalizuar gabimesh