Web Site
Developers

Dynamic Content - Missing Files Error Catching

Different Problem, Different Approach and Different Code

In the two previous articles my focus was on the catching an error where it was impossible to generate any valid menu, even the many of the meta tags in the head(er) section were unknown. The next possible error of significance to be examined here is the case where the menu should exist, but the file that contains the appropriate listing and links is absent. Again it is impossible to generate the menu, but for a differing underlying reason. Moreover, the severity is no less than the first set, it is just found later in the process.

This time I wish to exhibit a coding syntax I admired in Java, but had not known it was available in php and other scripting languages [1.]. The syntax I have in mind is the try / catch (exception) that is easily insertable into the existing code in the page template. Finally, in the summary, I will touch upon what follows.

Quick Review of the Essentials

In the last two articles, a fatal error was detected early in the process. Moreover, it was dealt with primarily in the head(er) section of the menu web template page. That is, the passed code for the menu was unknown, hence, code was fired to send immediate email warnings to pertinent addresses and a Boolean variable was flipped from false to true. The latter specifies also an important error has been found and makes certain a message must be sent to the user.

The first instance attempts to inform the user by redirecting the error message to an external page. The second instance had the menu template retained to inform the user by placing the message were the menu listing would have appeared. Where these two instances differed was, the second kept the template and moved the user error notification deeper into the template page. I will begin at the same second code location [2.], introducing new code checking for a potential missing file error.

Terse Mention of an Alternative

If one preferred to keep the error testing and response in the header section, the existence of the menu listing text file could be confirmed there. However, for the really paranoid that would not suffice. As I was asked essentially, what if I confirm the file exists in the head tag section, only to find later the readfile() function finds no file? Speaking for myself, I would let it crash, because, most likely, the problems are much more severe than a simple missing text file. Now lets proceed in the direction I indicated.

Older Code Structure

In my template, my checking code would begin in the main central column just below my header div for the menu page. The older skeleton looks like this:

   <div id="central-col-bst">
      <?php
          if ($if_error==false) {
	     readfile($menus . "/menu-list-".$get_it.".txt");
	     // prints the menu link listing
	  } else {
	     $gohome = $_SERVER['DOCUMENT_ROOT']."/[path]";
	     readfile($menus."/menu-not-known.txt");
	     readfile($gohome."/home-button.txt");
	     // prints user error message that includes an
	     // email link to the webmaster and return button
	  }	    
      ?>

    </div>   <!-- End of central B/ST column -->  

where the $get_it variable was the code value for the specific menu passed by the $_GET mentioned several times in the previous articles. This time we think the menu should exist, however, we must confirm that the menu listing exists. The alternative is a perplexing message to the user about an apparent coding error that is both confusing and uninformative.

Preferred Code Syntax

As I mentioned in the introduction, I had not known the try / catch syntax existed in php, however, it impressed me during my glancing brush [3.] with Java. Moreover, it is my suspicion that had I used it as part of the redirection code I might have been completely successful moving the error message to an external page. Nonetheless, the value I see in this syntax is its ability to seamlessly execute code that allows a graceful exit when a fault is discovered [4.]. In this article, I wish to show you how it can be applied.

Adapting Code Structure

The initial insertion of the code that will detect the missing menu list if within the if ($if_error==false), where the basis structure seems simple. That is, we go from this:

     <div id="central-col-bst">
       <?php
	 if ($if_error==false) {
	    readfile($menus . "/menu-list-".$get_it.".txt");
	       
	 } else {
	   ...
	 }	    
      ?>

    </div>   <!-- End of central B/ST column -->  

to the structure just below. However, please note the missing code [5.] denoted by the ellipsis is documented in the code further above. Now we test for the second major potential menu failure type:

   <div id="central-col-bst">
     <?php
        if ($if_error==false) {
          try {
	     // the file is the actual menu with appropriate links 
	     // and descriptions.
	     $file_exists = file($menus . "/menu-list-".$get_it.".txt");
	     if ($file_exists === FALSE) {
	        throw new move_onException($e);
	     } else {
	       readfile($menus . "/menu-list-".$get_it.".txt");
	     }

	   } catch (Exception $e) {
	      $if_error = true;
	      ...
	   }
	 } else {
	   ...
         }	    
      ?>

   </div>   <!-- End of central B/ST column -->  

This time time there are several features that should be noted, however, not all will be fully explained in this installment. First I draw your attention to new ellipsis after the catch exception portion of the syntax, there really is no added code, purposely. Due to priority of informing those responsible for the site is of greater importance than sending a message to the user that an error has been encountered. So only the $if_error variable is flipped. Further down the code, the email runs first followed by the user error message.

Returning to the need to inform the webmaster and cohorts, the new message should differ from the previous version. The need is to explicitly say the menu listing is absent. The user error message is of lesser importance, particularly if the email to the webmaster's addresses works.

Perhaps, what is of paramount importance is the line that creates an instance of the Exception class and in this case, a specific subclass of the just mentioned class. Without the explicit presence the exception bject the catch code would not be run. For now, please accept that as my assertion.

Sending the Messages

The generated error code will be fired outside the code section shown above. Beneath is a partial showing of that revised message:

  <div id="central-col-bst">
     <?php
        if ($if_error==false) {
	   try {
	      // $file_exists - file test
	      if ($file_exists === FALSE) {
		 // throw Exception($e);
	      } else {
	         // otherwise read the file
	      }
	   } catch (...) {
	      $if_error = true; // indicates text file
		                // missing
	} else {
	  // send menu unknown user message
	  // should reset $if_error to false
	}
	// New code
	if ($if_error==true) {
	   $to       = "webmaster@example.com, admin@other.net, ...";
	   $file     = "/menu-list-".$get_it.".txt'";
	   $subject  = "Menu Failure ".$file." text file not found";
	   $message  = "No Menu text file match with ".$file."\n";
	   $message .= "Confirm failure and see if you can find \
	                  text file for the menu\n";
	   ...
	}
	    	    
     ?>

  </div>   <!-- End of central B/ST column -->  

If you look at figure 2 in my article on hybrid security approach, you will see a successful transmission of a test message for the code listed above [6.]. What should have been included was a revised user message after the email above was executed and sent. However, in my haste I used the same message I used in the prior two articles. Therefore, I see no sense displaying the image again.

Summary of Results

I have shown you a rather straight forward method to catch another class of significant errors. In this case, it is checking for missing files. Other problems such as mangled content would not be caught [7.] by the exhibited code. I am purposely leaving some significant details out of this presentation. Those will discussed separately later.

Other items on the menu page template might be absent at run time, e.g. the various logos and images. Those have an alternate text description, while that might be ascetically displeasing it should suffice. An absent logo will not interfere with the prime function of a menu page, hence, their absence is not critical.

Future Presentations - Missing Code Details

If the forgoing left you a bit uneasy, that is to be expected. I skipped over a great deal. I ignored potential problems and failed to mention critical code details. Those will be attended to in a separate article beginning with a more detailed look at the try / catch syntax. I will also mention how it is possible to misinterpret how it functions.

One problem is my seeming to dump similar code functionality, but with varying context and content in too many places in the web page template. Obviously, that could become a nightmare to maintain. I intend to talk about modularization of the code to create a simpler package. However, I might not include it as part of the next article. If I temporally ignore this issue, I am just attempting to control the complexity of my explanations.

By rights, I should have shown the code for the supposed subclass of the Exception class. It was in the template page code, but it would not have added clarity. Moreover, at this stage and considering how little use I made of that object, I am reverting to using simply an instance of the built-in Exception class. We will look at the details of the try / catch syntax and its associated object oriented code in the next installment.

Corrections, suggested extension or comments write: H. Cohen. If the mailto does not work, use this: hcohen[-At-]bst-softwaredevs.com.

     © Herschel Cohen, All Rights Reserved

Return B/ST Home or Dynamic Menu Page
____________________________________________________________________

    1.  I already knew a form existed in Python, albeit with a 
        slightly differing syntax.  Nonetheless,  I was shocked to 
	learn it also could be found in perl.  Return

    2.  Look at the last article, to see the older code so that I 
        can avoid to much duplication.  Return

    3.  Note, at best I thought I could read Java code.  Return

    4.  In my recent reading on this topic, the recoverable 
        errors do not include flawed code.  That is, we are 
	attempting to catch intermittent system failures, such 
	as the absence of a network connection.  Or the absence 
	of an expected imported file that failed to be found due 
	to a transmission error. This  revised impression comes 
	from reading selected portions of: "Core Java 2; Volume 1
	- Fundamentals" where it differentiates between errors and 
	exceptions.  That is, the latter means thecode is right, 
	something expected is missing.  Return

    5.  This contains the original error message code.  Return

    6.  The email failure notice process was discussed earlier.  
        Return  

    7.  However file_size() run after file_exists() could catch 
        an empty file.  Return