2015-09-23 49 views
0

我想用我的自定義錯誤消息自定義異常錯誤按如下:PHP - 自定義異常錯誤

try { 
     $test = 1/0; 
    } 
    catch(Exception $ex){ 
     $t=time(); 
     $timelog = date("dmYhms",$t); 
     error_log($timelog."=> ErrorID: ".$timelog."\n", 3, "../error_log/Error.log"); 
     echo "System having issue with this request.\n 
       Transaction ID: ".$timelog; 
    } 

我的期望是,我要echo管理的自定義消息而不是默認的消息,我設法寫入日誌文件。但是,我仍然獲得了默認的錯誤信息,而不是下面的圖片中的自定義錯誤信息。 enter image description here

任何想法,我做了錯誤。請指教。

EDITED

error_reporting(0); 
//error handler function 
function customError($errno, $errstr) { 
    //echo "<b>Error:</b> [$errno] $errstr<br>"; 
    $t=time(); 
    $timelog = date("dmYhms",$t); 
    echo "Unable to process with the request. \n Error ID".$timelog.". PLease contact RND team."; 
    error_log($timelog."=> Error: [$errno] $errstr\n", 3, "error_log/Error.log"); 
} 

//set error handler 
set_error_handler("customError",E_USER_WARNING); 

//trigger error 
$username = "xxx"; 
$password = "xxx"; 
$host = "xxxx"; 
$dbname = "xxx"; 

$db = new mysqli($host, $username, $password,$dbname); 
if ($db->connect_error) { 
    trigger_error($db->connect_error,E_USER_WARNING); 
} 

上述編輯樣品工作正常,但,這是最好的做法。請指教。

+0

你可以閱讀這個quetion,我希望它能幫助你。 http://stackoverflow.com/questions/1241728/can-i-try-catch-a-warning – user39291

回答

0

這也不例外。你試圖捕捉一個錯誤。你需要設置你的錯誤處理函數來轉換錯誤/警告等來拋出異常。在PHP7中,它將被更改,您將能夠捕獲Error\Throwable接口

要將異常更改爲異常,您需要使用函數。您也可以找到this有趣

編輯:

<?php 

error_reporting(E_ALL); 
//error handler function 
function customError ($errno, $errstr) { 
    if (error_reporting() == 0) { 
     return; 
    } 
    $timelog = date("d-m-Y h:i:s", time()); 
    throw new Exception($timelog . ':' . $errstr, $errno); 
} 

//set error handler 
set_error_handler("customError", E_ALL & ~E_NOTICE); 
//trigger error 
try { 
    $error = 5/0; 
} catch(Exception $e) { 
    echo "Error caught : " . $e->getMessage(); 
} 

?> 

這仍然是非常基本的例子。如果您創建自己的異常類,並且處理錯誤優先級更好,那將會更好。

+0

我已經編輯與你的建議的答覆。這是最佳做法嗎? –

+0

不,它不是。如果你想這樣,這個函數應該會拋出異常,並且你應該在應用中處理異常。另外請注意,有時通知例外情況是無意義的 – Robert

+0

您是否有任何可能將您的代碼更改爲您的建議。我可以得到更清晰的圖片。 –