2012-06-05 24 views
2

由於PHP的unlink()本機不支持異常,我正在爲它製作一個包裝函數。如果給定的文件由於不存在而無法刪除,它應該拋出FileNotFoundException如何可靠地識別PHP中的特定錯誤?

爲此,我需要確定unlink()引發的錯誤是由缺少的文件還是其他內容引起的。

這是我的測試版自定義刪除功能:

public function deleteFile($path){ 
    set_error_handler(function($errLevel, $errString){ 
     debug($errLevel); 
     debug($errString); 
    }); 
    unlink($path); 
    restore_error_handler(); 
} 

對於$errLevel$errString我得到(E_WARNING)和取消鏈接(/ tmp目錄/ fooNonExisting):沒有這樣的文件或目錄

一個頗爲大膽的做法是這樣的:

if(strpos($errString, 'No such file or directory') !== false) { 
    throw new FileNotFoundException(); 
}; 

問題1:在不同的PHP版本中,我可以依賴多少錯誤字符串?問題2:有更好的方法嗎?

回答

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。

+1

是的,很好的解決方案。但是這也會掩蓋所有其他類型的問題,如錯誤的文件權限。我寧願只將「未找到文件」轉換爲異常。 – pixelistik

+0

我明白了,我更新了我的答案。 – powtac

+0

我修改了你的解決方案(正在等待審覈),在'else'塊中用'unlink()'我們可以擺脫糟糕的'@'部分。我可能會使用這種技術,但是讓我們等待其他關於初始錯誤處理/識別問題的答案。 – pixelistik

0

我相信它(即你的代碼)應該足夠便攜,因爲它是... 關於更好的方式來實現同樣的事情,我會做不同的事情(儘管代碼很簡單,它也更具可讀性...所以忍受着我)

function deleteFile($file_path){ 
    if(!is_file($file_path)){ 
     throw new Exception("The path does not seem to point to a valid file"); 
    } 
    if(!file_exists($file_path)){ 
     throw new Exception("File not found!"); 
    } 
    if(unlink($file_path)){ 
     return true; 
    } else { 
     throw new Exception("File deletion failed!"); 
    } 
} 

當然,你總是可以壓縮和改善代碼...跳這有助於!

0

我見過php錯誤信息多年來變化很大。也許,嘗試通過非常細粒度的代碼檢測最後一個錯誤的變化,然後導致字符串解析非常鬆散。

$lastErr = error_get_last(); 
unlink($file); 
if ($lastErr !== error_get_last()) { 
    // do something 
    //maybe string parsing and/or testing with file_exists, is_writable etc... 
} 
1

儘管通讀我的老questions我穿過ErrorException來了,與set_error_handler()相結合,這將是一個自動錯誤到異常的變壓器對所有本機PHP錯誤:

function exception_error_handler($errno, $errstr, $errfile, $errline) { 
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline); 
} 
set_error_handler("exception_error_handler"); 

/* Trigger exception */ 
unlink('Does not exitsts'); 

人教這個?

+1

它不適用於每個錯誤。除了解析器時間和啓動錯誤之外,其他一些運行時錯誤(如致命錯誤)也不會被任何錯誤處理程序捕獲。 –