คลาส ErrorException

คลาส ErrorException สืบทอดมาจากคลาสพื้นฐาน Exception และถูกใช้ เพื่อแปลงข้อผิดพลาด PHP เป็นข้อยกเว้น โดยเพิ่มข้อมูลเกี่ยวกับระดับความรุนแรงของข้อผิดพลาด (severity) เข้าไปในฟังก์ชันการทำงานมาตรฐานของข้อยกเว้น คลาสนี้มีประโยชน์เป็นพิเศษ เมื่อใช้ร่วมกับฟังก์ชัน set_error_handler

ไวยากรณ์

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

ตัวอย่าง

มาสร้างและจัดการ ErrorException กัน:

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

ผลลัพธ์การทำงานของโค้ด:

php'Error: Critical error Severity: 1'

ตัวอย่าง

แปลงข้อผิดพลาดมาตรฐาน PHP เป็นข้อยกเว้น:

php<?php
  function errorHandler($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
  }

  set_error_handler('errorHandler');

  try {
    strpos(); // จำนวนอาร์กิวเมนต์ไม่ถูกต้อง
  } catch (ErrorException $e) {
    echo 'Caught exception: ' . $e->getMessage();
    echo ' in ' . $e->getFile();
    echo ' on line ' . $e->getLine();
  }
?>

ผลลัพธ์การทำงานของโค้ด (ตัวอย่าง):

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

ตัวอย่าง

รับข้อมูลเกี่ยวกับระดับความรุนแรงของข้อผิดพลาด:

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

ผลลัพธ์การทำงานของโค้ด:

php'Severity level: 2 Is warning: yes'

ดูเพิ่มเติม

  • คลาส Exception,
    คลาสพื้นฐานสำหรับข้อยกเว้นทั้งหมดใน PHP
  • ฟังก์ชัน set_error_handler,
    ซึ่งกำหนดตัวจัดการข้อผิดพลาดแบบกำหนดเอง