0
我正在使用API服務器,我想處理所有PHP錯誤和異常。 因此,當我向API服務器發出請求時,響應將始終保持一致 - 即使在發生致命的php錯誤或來自其他類的一些內部異常時也是如此。PHP錯誤/異常處理 - 隱藏錯誤,但處理它?
我想出了以下內容:
// Register Custom Error Handler
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'logs/php-errors.log');
function ErrorHandler($errno, $errstr, $errfile, $errline) {
HandleError($errstr, $errfile, $errline);
}
function ExceptionErrorHandler(Exception $e) {
HandleError($e->getMessage(), $e->getFile(), $e->getLine());
}
function ShutdownFunction() {
$error = error_get_last();
if (!is_null($error) && sizeof($error)) {
HandleError($error['message'], $error['file'], $error['line']);
}
}
function HandleError($message, $file, $line)
{
// Prepare Error Data
$error_data = 'File : '. basename($file) ."\r\n".
'Line : '. $line ."\r\n".
'When : '. date('l jS \of F Y h:i:s A') ."\r\n".
'Error : '. $message;
// Log Error To File
$h = fopen('logs/'. date('d-m-Y') .'.log', 'a');
fwrite($h, $error_data."\r\n----------------------------------------------------------------------\r\n\r\n");
fclose($h);
// Exit With Error
header('Content-type: application/json');
exit(json_encode(array(
'IsError' => true,
'ErrorMsg' => $message .' | '. basename($file) .':'. $line,
'Data' => ''
)));
}
set_error_handler("ErrorHandler");
set_exception_handler('ExceptionErrorHandler');
register_shutdown_function('ShutdownFunction');
爲了測試這一點,在我的文件中的一個我叫一個不存在的函數調用test()
,這是得到了所產生的響應:
<br />
<b>Fatal error</b>: Call to undefined function test() in <b>/home/www-data/public_html/ipos_api/api_methods.php</b> on line <b>11</b><br />
{"IsError":true,"ErrorMsg":"Call to undefined function test() | api_methods.php:11","Data":""}
爲什麼不是PHP錯誤(就在我的JSON響應之上)被隱藏?我已將display_error設置爲關閉。
任何想法?