2013-03-24 97 views
2

我試圖做類似的代碼這一個:如何捕獲require_once/include_once異常?

<?php 
$includes = array(
    'non_existing_file.php', //This file doesn't exist. 
); 

foreach ($includes as $include) { 
    try { 
     require_once "$include"; 
    } catch (Exception $e) { 
     $message = $e->getMessage(); 
     echo " 
      <strong> 
       <font color=\"red\"> 
       A error ocurred when trying to include '$include'. 
       Error message: $message 
       </font> 
      </strong> 
     "; 
    } 
} 

我已經試過require_onceinclude_once,但try catch不逮住例外。 我怎麼能抓住這個致命錯誤/警告異常?

回答

1

該解決方案(改編自here)工作的罰款對我說:

register_shutdown_function('errorHandler'); 

function errorHandler() { 
    $error = error_get_last(); 
    $type = $error['type']; 
    $message = $error['message']; 
    if ($type == 64 && !empty($message)) { 
     echo " 
      <strong> 
       <font color=\"red\"> 
       Fatal error captured: 
       </font> 
      </strong> 
     "; 
     echo "<pre>"; 
     print_r($error); 
     echo "</pre>"; 
    } 
} 
+0

@LSerni Edited =) – GarouDan 2017-01-26 13:51:20

5

這些函數拋出E_COMPILE_ERROR,並且不能像這樣捕獲。

要處理這些錯誤,請參閱set_error_handler

+0

謝謝,這是國際海事組織的問題的最佳解決方案。 – Zeus77 2015-04-25 21:20:01

10

由於include/require不會引發異常,請檢查您想包含的文件是否存在並且可讀。例如:

$inc = 'path/to/my/include/file.php' 

if (file_exists($inc) && is_readable($inc)) { 

    include $inc; 

} else { 

    throw new Exception('Include file does not exists or is not readable.'); 
} 
+0

我不想這樣,因爲問題不存在,就像文件存在,但需要它時。 – GarouDan 2013-03-24 14:00:54

+0

好點。一個額外的'is_readable'會好得多。 – passioncoder 2013-03-24 14:04:29

+1

'include file.php;'可以包含來自PHP包含路徑中任何地方的文件。所以'file_exists()'在這裏沒有意義......特別是如果程序員不知道包含路徑在用戶服務器上的外觀如何... – Peter 2014-09-08 21:29:46