Page 1 of 1

Error handling?

Posted: Thu Sep 15, 2005 4:01 pm
by spacebiscuit
Hi,

Is it possible to save the error output message printed to the screen. I am using php to execute SQL queries and when there is an error for example:

Warning: odbc_exec(): SQL error: [SoftVelocity Inc.][TopSpeed ODBC Driver][ISAM]ISAM Table Not Found, SQL state S0000 in SQLExecDirect in routines.php on line 381

Ideally I'd like the error message to be written/found in a variable, I am emailing the errors to myself and would like this info too.

Thanks in advance,

Rob.

Posted: Thu Sep 15, 2005 4:24 pm
by Sander
You can make your own error handler using set_error_handler.

Posted: Thu Sep 15, 2005 4:25 pm
by John Cartwright
Yes, this is usually done using a "database abstraction layer" if you search that term you'll find some well made ones ones.
Although you do not require one, it all boils down to passing your odbc_error to a function that will handle your errors.
You have have complicated error handlers that will handle all your error types, but in this case we'll have a simple error function to write a log

Code: Select all

//pseudo
function log_error($error) {
  fwrite()
  fclose()
  exit();
}

$result = odbc_query('SELECT * FROM `table`') or log_error(odbc_error());

Posted: Sat Sep 17, 2005 8:05 am
by spacebiscuit
Hi,

Thanks for the reply, that solution did not seem to work though, just to clarify I wan't the error output to the screen to be read into a variable.

Thanks,

Rob.

Posted: Sat Sep 17, 2005 8:25 am
by n00b Saibot
This should provide you a start... this is straight from one of my online projects after a little bit of shuffling & clearing...

Code: Select all

/*handle_error.php*/

// Define Our Own Error Handler...
function my_stylish_error_handler($nr, $text, $file, $line)
{ if (is_readable($file))
 {
  $source = file($file);
  $source = str_replace(array("&nbsp;","<code><font color=\"#000000\">","</font>\r\n</code>"), "", highlight_string('<?'.str_replace("\r\n","",$source[$line-1]).'?>', 1));
  $source = substr_replace($source, "", strpos($source, "<?"), 5);
  $source = substr_replace($source, "", strrpos($source, "<?")-1, 5);
 }
 else
 { $source = "<i>N/A</i>"; }
 catchErr("<span class=\"errEmph\">$text</span> in <span class=\"errEmph\">".str_replace('c:\\web\\ramarkz\\', '', $file)."</span><br />Line $line : <code class=\"errSrc\">\r\n\r\n$source\r\n\r\n</code>"); }
set_error_handler("my_stylish_error_handler");

// Catch an Error
function catchErr($Err)
{
 $_SESSION['ERRORS'][] = $Err;
}

// Output the Caught Errors
function writeErrors()
{
 if(count($_SESSION['ERRORS']) > 0):
  echo "<b>Error:</b><br />\r\n";
  foreach ($_SESSION['ERRORS'] as $Err)
   echo "&rArr; {$Err}<br />\r\n";
 endif;
}
include this file in your file and call writeErrors() which will display all errors wherever you call it. As you see, all the errors are caught & transferred into $_SESSION['ERRORS'] array.

Posted: Sat Sep 17, 2005 8:50 am
by Maugrim_The_Reaper
Basically set_error_handler() lets you assign a custom function you write to do literally anything with error messages. Whether you want to display in a nifty well presented HTML page, log to an XML file, or log to a database, or any combination of the above.

Giving an example of HTML Output:

Code: Select all

class Q_ErrorHandler_HTML {

	var $errorType = array ( 
		1   =>  'PHP Error', 
		2   =>  'PHP Warning', 
		4   =>  'PHP Parsing Error', 
		8   =>  'PHP Notice', 
		16  =>  'Core Error', 
		32  =>  'Core Warning', 
		64  =>  'Compile Error', 
		128 =>  'Compile Warning', 
		256 =>  'Application Error', 
		512 =>  'Application Warning', 
		1024=>  'Application Notice' 
	);

	var $userErrors = array(
		E_USER_ERROR,
		E_USER_WARNING,
		E_USER_NOTICE
	);

	var $data;
	
	function Q_ErrorHandler_HTML() {
		ini_set('docref_root', null);
        		ini_set('docref_ext', null);
	}

	function raiseError($errorNo, $errorMsg, $fileName, $lineNum, $vars) {

        while (ob_get_level()) {
		ob_end_clean();
        }

        if (($errorNo & E_USER_ERROR) && is_array($array = @unserialize($errorMsg))) {
            foreach ($array as $key => $val) {
                $this->data[$key] = $val;
            }
        }
        
        $trace = array();

        if (function_exists('debug_backtrace')) {
            $trace = debug_backtrace();
            array_shift($trace);
        }

		// set variable references to class variables
		$errorType =& $this->errorType;
		$info =& $this->data;

        include QLIBROOT . '/Classes/ErrorHandler/Error.tpl';
        exit();

		// or store to DB/XML as appropriate
    }
}
Notice the parameters? These are the data you're looking for - and probably some of the backtrace if you need that - $trace. You can use that data to either print to screen (similar to above - Error.tpl contains a few functions to organise the data and output it) or write off to a database. To use (the above is a single class - part of a larger collection of DB and XML variants instanced by a factory based on some preference) simply set the error handler somewhere in your code (prior to any errors is possible) similar to:

Code: Select all

require_once('ErrorHandler_HTML.php');
$error_handler = new Q_ErrorHandler_HTML();
set_error_handler(array($error_handler, 'raiseError'));