Reputation: 24116
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) ."\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');
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?
Upvotes: 0
Views: 487
Reputation: 24116
Figured out what the problem was.
I am using Nginx with PHP-FPM. On my php-fpm.d pool configuration, I had specified the display_errors
on, therefore it was over-writing all settings (in-line using ini_set and php.ini itslef).
After removing that config line and re-starting php-fpm, I was able to hide the error message and still handle it.
Upvotes: 1