6
\$\begingroup\$

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
  • in the prod environment the error information have to be logged whereas a generalized error message have to be shown on-screen.

It am going to distinguish the modes using display_errors php.ini parameter and also consider all cli scripts 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 a wast room for improvement, like to create distinct exception classes for each error type (Like DeprecatedErrorException, NoticeErrorException etc.) or, based on the severity, to decide whether the script execution have 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 denomonstrational example. What are essential additions or modifications could be made to this code?

\$\endgroup\$
1
\$\begingroup\$

Perhaps a more "friendly" message would be nice and/or a way to customize it. As an example the generic catcher we're using right now reads:

echo '<div style="width: 700px;">
<h3>Sorry but we ran into an unexpected problem.</h3>
The problem has been logged and support staff have been notified.
<h6>Please try again.</h6>
</div>';
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.