如何屏蔽PHP中的通知和警告?警告有時可以從一些代碼中刪除,當代碼中彈出警告提示時,用戶可進行適當選擇,其中包括將它們寫在錯誤日志中,或完全忽視。而Alexander Netkachev卻有不同的解決方案——通過內建在PHP中的例外報告來處理、該編碼技巧將展示如何通過try/catch語句以例外的方式來處理PHP通知和警告。
盡管這是一個很簡單的方案,但卻完全可以幫助用戶將所有的錯誤信息存儲在同一位置。Alexander Netkachev所提供的代碼示例既展示了基本的解決方案,也展示了其復雜的一面。另外,還為不同的例外類型提供了更詳細的信息。
代碼如下:
function errorHandler($errno, $errstr, $errfile, $errline) {
throw new Exception($errstr, $errno);
}
set_error_handler('errorHandler');
try {
file_put_contents('cosmos://1.txt', 'asdf');
} catch (Exception $e) {
echo $e->getMessage();
}
The code above throws an exception because the file cannot be saved. Then the exception is caught by the try/catch statement. With a little bit of additional error processing you can create even more reliable code:
class IOException extends Exception {}function errorHandler($errno, $errstr, $errfile
新聞熱點
疑難解答