由于 PHP 的 unlink()
本身不支持异常,因此我正在为其创建一个包装函数。如果给定文件因不存在而无法删除,则应抛出 FileNotFoundException
。
为此,我需要确定 unlink()
引发的错误是由丢失文件还是其他原因引起的。
这是我的自定义删除功能的测试版本:
public function deleteFile($path){
set_error_handler(function($errLevel, $errString){
debug($errLevel);
debug($errString);
});
unlink($path);
restore_error_handler();
}
对于 $errLevel
和 $errString
我得到 2 (E_WARNING) 和 unlink(/tmp/fooNonExisting): No such文件或目录
一个相当大胆的方法是这样的:
if( strpos($errString, 'No such file or directory') !== false ) {
throw new FileNotFoundException();
};
问题 1:在不同 PHP 版本中,我可以在多大程度上相信错误字符串是相同的?问题2:有更好的方法吗?
最佳答案
我会简化代码:
public function deleteFile($path){
if (!file_exists($path) {
throw new FileNotFoundException();
}else{
unlink($path);
}
if (file_exists($path) {
throw new FileNotDeleted();
}
}
那么你就不必捕获$errstr
并进行复杂的错误捕获。当引入异常时,它将工作到 PHP 4。
关于php - 如何可靠地识别 PHP 中的特定错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10899863/