How to email details of all PHP exceptions/errors, including mysqli ones?
one text
Solution:
First of all I must warn you that on a live site that is open to public, emailing errors could flood your mailbox in case of some critical failure when every request to the site causes a distinct email to be sent. It happened not once to the companies I worked for. And sometimes it's hard to find the actual cause in the waterfall of the errors.
Monitoring server logs is considered much safer and accurate solution. Using Grep on the error log proved to me much more efficient than browsing emails. But either way, the question here is how to handle all errors uniformly, while the action taken in the handler could be anything.
So just like it shown in my article on error reporting basics, errors and exceptions are different beasts and each has its own handler. Hence, to have the error processing uniform you have to convert errors to exceptions first, and then do the required processing in the exception handler, whatever it will be - logging, emailing or anything.
As such, you will need two functions featured in the article, the error handler that simply transfers errors into exceptions,
set_error_handler(function ($level, $message, $file = '', $line = 0)
{
throw new ErrorException($message, 0, $level, $file, $line);
});
and the exception handler like this
set_exception_handler(function ($e)
{
error_log($e);
http_response_code(500);
if (ini_get('display_errors')) {
echo $e;
} else {
error_log($e, 1, "myemailaddress@myserver.com", "From: defaultemail@hostingserver.com");
echo "<h1>500 Internal Server Error</h1>
An internal server error has been occurred.<br>
Please try again later.";
}
});
that will send you an email every time an error occurs and the code is run on a live site.
Also, you would probably like to add a fatal error handler which could be instrumental in handling the eponymous errors. The full example of all three handlers combined together can be seen in the article.
Regarding mysqli, you are absolutely right, the following line
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
will tell mysqli to throw exceptions, which will be processed by the handler defined above.
Source