Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP ErrorException

บทนำ

คลาส Exception ของ PHP implement interface Throwable คลาส ErrorException extends คลาส Exception ErrorException นี้ใช้เพื่อโยนอย่างชัดเจนเมื่อต้องการ catch และจัดการ errors ที่จะถูกละเลยไป เช่น Notices หรือ Warnings

PHP core มี predefined error constants ดังนี้

ValueConstantDescription
1E_ERRORFatal run-time errors
2E_WARNINGRun-time warnings (non-fatal errors)
4E_PARSECompile-time parse errors
8E_NOTICERun-time notices
16E_CORE_ERRORFatal errors ที่เกิดระหว่าง PHP startup
32E_CORE_WARNINGWarnings (non-fatal) ที่เกิดระหว่าง PHP startup
64E_COMPILE_ERRORFatal compile-time errors
128E_COMPILE_WARNINGCompile-time warnings (non-fatal)
256E_USER_ERRORUser-generated error message
512E_USER_WARNINGUser-generated warning message
1024E_USER_NOTICEUser-generated notice message
2048E_STRICTถ้าเปิด PHP จะแนะนำการเปลี่ยนโค้ดเพื่อ interoperability และ forward compatibility
4096E_RECOVERABLE_ERRORCatchable fatal error
8192E_DEPRECATEDRun-time notices
16384E_USER_DEPRECATEDUser-generated warning message
32767E_ALLAll 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