ErrorException Klassı

ErrorException klassi əsas Exception klassından miras alır və PHP səhvlərinin istisnalara çevrilməsi üçün istifadə olunur. O, standart istisna funksionallığına səhvin ciddiliyi (severity) haqqında məlumat əlavə edir. Bu klass xüsusilə set_error_handler funksiyası ilə birlikdə istifadə edildikdə faydalıdır.

Sintaksis

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

Nümunə

ErrorException yaradaq və emal edək:

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

Kodun icrasının nəticəsi:

php'Error: Critical error Severity: 1'

Nümunə

Standart PHP səhvlərini istisnalara çevirək:

php<?php
  function errorHandler($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
  }
  
  set_error_handler('errorHandler');
  
  try {
    strpos(); // Səhv arqument sayı
  } catch (ErrorException $e) {
    echo 'Caught exception: ' . $e->getMessage();
    echo ' in ' . $e->getFile();
    echo ' on line ' . $e->getLine();
  }
?>

Kodun icrasının nəticəsi (nümunə):

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

Nümunə

Səhvin ciddiliyi haqqında məlumat əldə edək:

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

Kodun icrasının nəticəsi:

php'Severity level: 2 Is warning: yes'

Həmçinin bax

  • klass Exception,
    PHP-də bütün istisnalar üçün əsas klass
  • funksiya set_error_handler,
    istifadəçi tərəfindən təyin olunan səhv emaledicini təyin edir