Kelas ErrorException

Kelas ErrorException mewarisi dari kelas dasar Exception dan digunakan untuk mengubah error PHP menjadi exception. Kelas ini menambahkan informasi tentang tingkat keparahan error (severity) ke fungsionalitas exception standar. Kelas ini sangat berguna saat digunakan dengan fungsi set_error_handler.

Sintaks

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

Contoh

Membuat dan menangani ErrorException:

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

Hasil eksekusi kode:

php'Error: Critical error Severity: 1'

Contoh

Mengubah error standar PHP menjadi exception:

php<?php
  function errorHandler($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
  }
  
  set_error_handler('errorHandler');
  
  try {
    strpos(); // Jumlah argumen yang salah
  } catch (ErrorException $e) {
    echo 'Caught exception: ' . $e->getMessage();
    echo ' in ' . $e->getFile();
    echo ' on line ' . $e->getLine();
  }
?>

Hasil eksekusi kode (contoh):

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

Contoh

Mendapatkan informasi tentang tingkat keparahan error:

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

Hasil eksekusi kode:

php'Severity level: 2 Is warning: yes'

Lihat juga