分类:
2008-04-14 17:48:33
该编码技巧将展示如何通过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, $errline) { if (false !== substr('failed to open stream', $errstr)) { throw new IOException($errstr, $errno); } throw new Exception($errstr, $errno); } set_error_handler('errorHandler'); try { file_put_contents('cosmos:\\1.txt', 'asdf'); } catch (IOException $e) { echo 'IO exception: ' . $e->getMessage(); } catch (Exception $e) { echo 'Unknown exception: ' . $e->getMessage(); }
原文地址: