健壯的 PHP 應用離不開完善的錯誤處理策略。本文系統梳理基礎錯誤處理、自定義錯誤處理器、錯誤觸發與錯誤級別常量,幫助開發者構建可維護的錯誤管理體系。
<?php
// 簡單判斷文件是否存在
if (!file_exists("welcome.txt")) {
die("File not found");
} else {
$file = fopen("welcome.txt", "r");
}
// 簡寫寫法
$file = fopen("webdictionary.txt", "r") or die("Unable to open file!");
?>
die(status):status 為字符串時輸出並退出;為整數(0-254)時作為退出狀態碼(255 保留,0 表示成功)。
簽名:error_function(int $errno, string $errstr, string $errfile, int $errline, array $errcontext)
<?php
function customError($errno, $errstr) {
echo "<b>Error:</b>[$errno] $errstr <br/>";
echo "Ending Script";
die();
}
?>
| 值 | 常量 | 描述 |
|---|---|---|
| 2 | E_WARNING | 非致命運行時錯誤,腳本繼續執行 |
| 8 | E_NOTICE | 運行時通知,潛在問題但不一定是錯誤 |
| 256 | E_USER_ERROR | 用戶觸發的致命錯誤(via trigger_error) |
| 512 | E_USER_WARNING | 用戶觸發的非致命警告 |
| 1024 | E_USER_NOTICE | 用戶觸發的通知 |
| 4096 | E_RECOVERABLE_ERROR | 可捕獲的致命錯誤,可由 set_error_handler 捕獲 |
| 8191 | E_ALL | 所有錯誤與警告(PHP 6.0+ 包含 E_STRICT) |
<?php
// 處理所有錯誤
set_error_handler("customError");
// 僅處理特定級別(如僅警告與通知)
set_error_handler("customError", E_WARNING | E_NOTICE);
?>
默認內建處理器會被替換,可針對不同級別註冊不同處理函數。
<?php
$test = 2;
if ($test > 1) {
trigger_error("Value must be 1 or below", E_USER_WARNING);
}
?>
常用類型:E_USER_ERROR、E_USER_WARNING、E_USER_NOTICE。
display_errors,啟用 log_errors 寫入日誌文件。set_exception_handler() 捕獲未處理異常,實現統一錯誤頁面。Throwable 接口統一了 Error 與 Exception,建議使用 try-catch 處理可預期異常。