บทนำ
คลาส Exception ของ PHP implement interface Throwable คลาส ErrorException extends คลาส Exception ErrorException นี้ใช้เพื่อโยนอย่างชัดเจนเมื่อต้องการ catch และจัดการ errors ที่จะถูกละเลยไป เช่น Notices หรือ Warnings
PHP core มี predefined error constants ดังนี้
| Value | Constant | Description |
|---|---|---|
| 1 | E_ERROR | Fatal run-time errors |
| 2 | E_WARNING | Run-time warnings (non-fatal errors) |
| 4 | E_PARSE | Compile-time parse errors |
| 8 | E_NOTICE | Run-time notices |
| 16 | E_CORE_ERROR | Fatal errors ที่เกิดระหว่าง PHP startup |
| 32 | E_CORE_WARNING | Warnings (non-fatal) ที่เกิดระหว่าง PHP startup |
| 64 | E_COMPILE_ERROR | Fatal compile-time errors |
| 128 | E_COMPILE_WARNING | Compile-time warnings (non-fatal) |
| 256 | E_USER_ERROR | User-generated error message |
| 512 | E_USER_WARNING | User-generated warning message |
| 1024 | E_USER_NOTICE | User-generated notice message |
| 2048 | E_STRICT | ถ้าเปิด PHP จะแนะนำการเปลี่ยนโค้ดเพื่อ interoperability และ forward compatibility |
| 4096 | E_RECOVERABLE_ERROR | Catchable fatal error |
| 8192 | E_DEPRECATED | Run-time notices |
| 16384 | E_USER_DEPRECATED | User-generated warning message |
| 32767 | E_ALL | All errors and warnings, E_STRICT |
นอกจาก properties และ methods ที่สืบทอดมาจาก Exception class แล้ว ErrorException class เพิ่ม property และ method หนึ่งดังนี้
protected int severity ; final public getSeverity ( void ) : int
Severity ของ exception แทนด้วยจำนวนเต็มที่สอดคล้องกับประเภทข้อผิดพลาดในตารางข้างต้น
ErrorException example
ในสคริปต์ต่อไปนี้ ฟังก์ชัน user-defined errhandler ถูกตั้งเป็น Error handler ด้วยฟังก์ชัน set_error_handler() มันโยน ErrorException เมื่อพบ fatal error จากไฟล์ไม่พบสำหรับอ่าน
ตัวอย่าง
<?php function errhandler($severity, $message, $file, $line) { if (!(error_reporting() & $severity)) { echo "no error"; return; } throw new ErrorException("Fatal Error:No such file or directory", 0, E_ERROR); } set_error_handler("errhandler"); /* Trigger exception */ try{ $data = file_get_contents("nofile.php"); echo $data; } catch (ErrorException $e){ echo $e->getMessage(); } ?>ตัวอย่างข้างต้นแสดงผลลัพธ์ดังนี้
ผลลัพธ์
Fatal Error:No such file or directory