Hi folks!

doing a wee bit of research!

just interested in everyones opinion about error handling.

Do you prefer to use the True/False method or to trap the error using set_error_handler("function_handle");

cheers!

    What's the "true/false" method?

    PHP errors such as Notices, Warnings, Parse Errors are going to happen if you have bugs in your code no matter what.

    So you should of course use the set_error_handler() function to properlly handle those errors. Generally those error messages are of no use to the user, so what I do is use set_error_handler() to call a function that emails me the error instead of displaying to the user.

    This is very usefull in finding bugs lurking deep within your code, and keeping the code bug-free.

    Maybe you meant by "true/false" custom user errors? like

    if($var == 1){
    trigger_error("sorry that is an incorrect value", E_USER_ERROR);
    return false;
    }

    which in that case I would throw an error using trigger_error() function with E_USER_ERROR.

    This would of course call the function set by set_error_handler() but I would generally have this function displaying E_USER_ERROR type errors instead of emailing them to me.

    Check out the php documentation for more info on stuff you can do when writing error handling functions.

    cya
    -Adam 🙂

      23 days later

      Hi Adam,

      Would you mind posting the mentioned set_error_handler() function code?

      I think I could use something like it.

      Thanks,
      John

        set_error_handler() is part of PHP. Not user defined function.

          Hi, no worries here's the code.

          To neon, yes set_error_handler() is a php function to set your own error handling function which you can write yourself.

          Read on to see how.

          
          //Function to print an array
          function p_arr($arr) {
              foreach($arr as $k=>$v)
                  $out[] = "<tr><td colspan=3>&nbsp;</td><td valign=top>" . htmlentities($k) ." => " . gettype($v) . " " . htmlentities($v) . "</td></tr>";
              return implode("\n", $out);
          }
          
          //Function to get information on an object
          function objectInfo($obj) {
              $out[] = "<table style='color:#A9A9A9;'><tr><td valign=top><b>Class:</b> ".get_class($obj) . "<BLOCKQUOTE dir=ltr style=\"MARGIN-RIGHT: 0px\"><table style='color:#A9A9A9;'>";
              foreach(get_object_vars($obj) as $var=>$val)
                  if (is_array($val))
                      $out[] = "<tr><td valign=top><b>property:</b></td><td valign=top>" . $var . " </td><td valign=top>array </td><td>&nbsp;</td></tr>" . p_arr($val);
                  elseif(is_bool($val)){
                  	$temp = "<tr><td valign=top><b>property:</b></td><td valign=top>" . $var . "</td><td valign=top>boolean </td><td valign=top>";
                  	if($val)
                  		$temp .= "true";
                  	else
                  		$temp .= "false";
                  	$out[] = $temp . "</td></tr>";
                  }
                  else
                      $out[] = "<tr><td valign=top><b>property:</b></td><td valign=top>" . $var . "</td><td valign=top>" . gettype($val) . " </td><td valign=top>" . $val . "</td></tr>";
              foreach(get_class_methods($obj) as $method)
                  $out[] = "<tr><td valign=top><b>method:</b></td><td valign=top>" . $method . "</td><td colspan=2>&nbsp;</td></tr>";
          
          $out[] = "</table></BLOCKQUOTE></td></tr></table>";
          return implode("\n", $out);
          }
          
          //Print out array in a table
          function printGlobals($vars, $bOutput = false){
          	$sMessage = "\n<table cellspacing=0 cellpadding=2 border=0 style='font-size:8pt; font-family: Lucida Console;'>";
          	foreach((array)$vars as $key => $value){
          		if(is_array($value) && $key != "GLOBALS"){
          			$sMessage .= "\n<tr><td valign=top><font color=red>" . $key . "</font></td><td valign=top>array </td><td>";
          			$sMessage .= printGlobals($value, false);
          		}
          		else{
          			if(is_object($value))
          				$sMessage .= "\n<tr><td valign=top>" . $key . "</td><td valign=top>object </td><td style='color:#A9A9A9;'>" . objectInfo($value) . "</td></tr>";
          			else
          				$sMessage .= "\n<tr><td valign=top>" . $key . "</td><td valign=top>" . gettype($value) . " </td><td style='color:#A9A9A9;' valign=top>" . htmlentities((string)$value) . "</td></tr>";
          		}
          	}
          	$sMessage .= "\n</td></tr></table>\n";
          
          if($bOutput)
          	echo $sMessage;
          else
          	return $sMessage;
          }
          
          //Actual error handling function. This is called automatically on an error.
          //The arguments are automatically passed to by php
          function ErrorHandler($errno, $errmsg, $filename, $linenum, $vars){
          	global $oSession;
          
          switch($errno){
          	case E_ERROR: $sError = "Error"; $sColor = "#EAF9F3"; break;	
          	case E_PARSE: $sError = "Parse"; $sColor = "#EAF0F9"; break;
          
          	case E_WARNING: $sError = "Warning"; $sColor = "#F8F9EA"; break;
          	case E_NOTICE: $sError = "Notice"; $sColor = "#F9EAF7"; return;
          
          	case E_CORE_ERROR: $sError = "Core"; $sColor = "#EFF9EA"; break;
          	case E_CORE_WARNING: $sError = "Core warning"; $sColor = "#EAF9F4"; break;
          	case E_COMPILE_ERROR: $sError = "Compile error"; $sColor = "#F9ECEA"; break;
          	case E_COMPILE_WARNING: $sError = "Complile warning"; $sColor = "#F0FFFF"; break;
          
          	case E_USER_ERROR: $sError = "User error"; $sColor = "#FFFAF0"; break;
          	case E_USER_WARNING: $sError = "User warning"; $sColor = "#FAFAD2"; break;
          	case E_USER_NOTICE: $sError = "User notice"; $sColor = "#F5FFFA"; break;
          
          	default: $sError = "Unknown"; $sColor = "#FFE4E1"; break;
          }
          
          $dtDate = date('Y-m-d H:i:s');
          
          $sMessage = "<table cellspacing=0 cellpadding=2 border=0 style='border:1px #A9A9A9 solid;'>
          	<tr style='background-color:$sColor;'><td><b>Type</b></td><td>" . $sError . "</td></tr>
          	<tr><td><b>Script:</b></td><td>" . $_SERVER["SCRIPT_NAME"] . "?" . $_SERVER["QUERY_STRING"] . "</td></tr>
          	<tr style='background-color:$sColor;'><td><b>Date:</b></td><td>$dtDate</td></tr>
          	<tr><td><b>Remote Address:</b></td><td>" . $_SERVER['REMOTE_ADDR'] . "</td></tr>
          			<tr><td><b>Filename:</b></td><td>$filename</td></tr>
          	<tr><td style='background-color:$sColor;'><b>Referer:</b></td><td><a style='text-decoration:none;' href=\"" . $_SERVER["HTTP_REFERER"] . "\">" . $_SERVER["HTTP_REFERER"] . "</a></td></tr>
          	<tr><td><b>Line number:</b></td><td>$linenum</td></tr>
          	<tr><td style='background-color:$sColor;'><b>Error Message:</b></td><td>$errmsg</td></tr>
          	<tr><td valign=top><b>Variables:</b></td><td>";
          
          $sMessage .= printGlobals($vars, false);
          
          $sMessage .= "</td></tr></table>";
          
          $sHeaders  = "MIME-Version: 1.0\r\n";
          $sHeaders .= "Content-type: text/html; charset=iso-8859-1\r\n";
          $sHeaders .= "From: " . WEBSITE_TITLE . " Administration <" . WEBSITE_EMAIL_ADDRESS . ">\r\n";
          
          $sSubject = WEBSITE_TITLE . " PHP Error - " . $sError;
          
          if(NOTIFY_EMAIL_ERROR)
          	mail(WEBMASTER_EMAIL_ADDRESS, $sSubject, $sMessage, $sHeaders);
          }
          
          //Set global constant variables
          define("WEBSITE_EMAIL_ADDRESS", "email@domain.com");
          define("WEBMASTER_EMAIL_ADDRESS", "webmaster@domain.com");
          define("WEBSITE_TITLE", "mysite.com");
          define("NOTIFY_EMAIL_ERROR", 1");
          
          //Turn errors off so users cannot see them
          error_reporting(0);
          
          //Set error  handler and store the old error handler	
          $old_error_handler = set_error_handler("ErrorHandler");
          
          

          include that code on every page (in a seperate file preferably) and you should get emailed when errors occor in your scripts.

          The actual script I use on my site is slightly modifed. I only send an email if I'm not the one who's viewing the page.

          That is, if I am viewing the page there is no need to send an email, and I just print to the screen. You should prolly add that in yourself as I've no way to know how your user backend part works.

          The script provides lots of usefull information on an error, including info on the variables involved in the error.

          Also notice that I do this for E_NOTICE errors:

          case E_NOTICE: $sError = "Notice"; $sColor = "#F9EAF7"; return;
          

          I just return, as they're kind of fickle sort of errors and I don't care about them. If you do, then just change the 'return' to a 'break' and it will process them too.

          k, hope the code is usefull to you.

          -Adam 🙂

            thanks for posting the script, I gave it a try but still see errors and get no email. No functions have to be called right, just include it?

            I tried making a parse error but they appear, sample:
            Parse error: parse error, unexpected '\"' in /home/public_html/test.php on line 111

              The parse error you're getting is cause there's an accidental typo here:

              define("NOTIFY_EMAIL_ERROR", 1");

              I missed out a ". Whoops. How embarrasing 😉

              Just change to
              define("NOTIFY_EMAIL_ERROR", "1");

              also, make sure you've set all the constants - your email address mainly.

              To test just calling a function that doesn't exist or something. eg:

              superduperfunction($fdsjl);

              lol. that should work.

              cya. Let me know how it goes

              -Adam 🙂

                No functions have to be called right, just include it?

                Oh yeah, I meant to say that's correct as well. PHP will call the ErrorHandler() function automatically once it is set to.

                The other functions can be called though in your scripts for debugging purposes if you like. I use them all the time for information on variables.

                Eg:

                //Print information on all php variables
                printGlobals($GLOBALS, true);
                
                
                //Print information on an object.  Make sure it exists first, unlike here
                objectInfo($oMyObject);
                

                cya
                -Adam 🙂

                  Write a Reply...