Custom Errors from a File
-
19-09-2019 - |
Question
I'm trying to read a file when ever an error occurs within my scripts so I can throw a custom error page.
When using ob_start/set_error_handler I am unable to use file_get_contents or ob_start within the callback to get the contents of my error template.
Does anyone know how I can output my custom template (and using eval) within the callback?
Edit: Some code
error_reporting(E_ALL);
ini_set("display_errors", 1);
function fatal_error_handler($buffer) {
if (ereg("(error</b>:)(.+)(<br)", $buffer, $regs) ) {
$ErrorString = preg_replace("/<.*?>/","",$regs[2]);
error_log($ErrorString);
$template = file_get_contents(sprintf('%s/errors/Error.php', TEMPLATES));
return eval(sprintf('?>%s<?', $template);
//return "ERROR CAUGHT check log file";
}
return $buffer;
}
function handle_error ($errno, $errstr, $errfile, $errline)
{
error_log("$errstr in $errfile on line $errline");
if($errno == FATAL || $errno == ERROR){
ob_end_flush();
echo "ERROR CAUGHT check log file";
exit(0);
}
}
ob_start("fatal_error_handler");
set_error_handler("handle_error");
The above just displays an empty page.
error_reporting(E_ALL);
ini_set("display_errors", 1);
function fatal_error_handler($buffer) {
if (ereg("(error</b>:)(.+)(<br)", $buffer, $regs) ) {
$ErrorString = preg_replace("/<.*?>/","",$regs[2]);
error_log($ErrorString);
ob_start();
include(sprintf('%s/errors/Error.php', TEMPLATES));
$template = ob_get_contents();
ob_end_clean();
return eval(sprintf('?>%s<?', $template));
//return "ERROR CAUGHT check log file";
}
return $buffer;
}
function handle_error ($errno, $errstr, $errfile, $errline)
{
error_log("$errstr in $errfile on line $errline");
if($errno == FATAL || $errno == ERROR){
ob_end_flush();
echo "ERROR CAUGHT check log file";
exit(0);
}
}
ob_start("fatal_error_handler");
set_error_handler("handle_error");
and the above gives the following:
Fatal error: ob_start() [<a href='ref.outcontrol'>ref.outcontrol</a>]: Cannot use output buffering in output buffering display handlers in /var/www/index.php on line 16
Solution
You have to :
- know that
file_get_contents
returns false when it encounters an error.- which means you can test its return value,
- and if it returned
false
, you can display your template
- also be careful : when there's a problem, it generates an error, and you don't want that one displayed
- this is the kind of situation for which you can use the @ operator,
- to "mask" the error -- you test if it returned false, anyway
It would give that kind of code :
$result = @file_get_contents('non-existing-file');
if ($result === false) {
echo "An error has occured";
}
Which, in my case, displays :
An error has occured
Now, up to you to display your error template, depending on the Framework you might be using and all that ;-)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow