I am trying to make a very simple error handler that would catch and handle all kinds of errors in both development and production environments. The idea is to keep it as simple as possible yet useful in the production environment.
In order to do so I am converting all errors into exceptions. Then I will need just a single function to handle both errors and exceptions.
Then, according to my principles of error handling
- in the dev environment, it should just echo the error information out, and
- in the prod environment, the error information has to be logged and a generalized error message has to be shown on-screen.
It am going to distinguish the modes using display_errors
php.ini parameter and also consider all CLI scripts to be in the dev mode too.
set_error_handler(function ($level, $message, $file = '', $line = 0)
{
throw new ErrorException($message, 0, $level, $file, $line);
});
set_exception_handler(function ($e)
{
if (ini_get('display_errors') || php_sapi_name() === 'cli') {
echo $e;
} else {
error_log($e);
header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
echo "<h1>500 Internal Server Error</h1>
An internal server error has been occurred.<br>
Please try again later.";
}
});
There is vast room for improvement, like to create distinct exception classes for each error type (such as DeprecatedErrorException
, NoticeErrorException
etc.) or, based on the severity, to decide whether the script execution has to be terminated or not. Or a more creative/user-friendly error message. But I am not sure if I should include all that in a simple demonstration example. What are essential additions or modifications could be made to this code?