I am working on an API server and I'd like to handle all PHP errors and exceptions. So, when ever I make a request to my API Server, the response will always be consistent - even during a fatal php error or some internal exception from my other class.
I came up with the following:
// 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) ."
".
'Line : '. $line ."
".
'When : '. date('l jS \of F Y h:i:s A') ."
".
'Error : '. $message;
// Log Error To File
$h = fopen('logs/'. date('d-m-Y') .'.log', 'a');
fwrite($h, $error_data."
----------------------------------------------------------------------
");
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');
To test this, on one of my files I called a non existing function called test()
and this is the response that got produced:
<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":""}
Why isn't the php error (just above my json response) being hidden? I've set the display_error to off.
Any ideas?