PHP
  Home arrow PHP arrow Page 3 - Error Handling in PHP: Coding Defensiv...
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Error Handling in PHP: Coding Defensively
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 38
    2006-01-11

    Table of Contents:
  • Error Handling in PHP: Coding Defensively
  • Killing your scripts: basic error handling with the “die()” statement
  • Triggering errors: more efficient error handling with the “trigger_error()” function
  • The PEAR way: looking at the PEAR_Error object
  • True and false: handling errors with Boolean flags

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Error Handling in PHP: Coding Defensively - Triggering errors: more efficient error handling with the “trigger_error()” function


    (Page 3 of 5 )

    As I explained in earlier examples, the “die()” statement can be used to build in rudimentary error handling mechanisms. But, particularly in mid-sized and large applications, this method isn’t flexible enough. As I said before, PHP provides developers with the “trigger_error()” function, which can be utilized for developing a slightly more sophisticated error handler.

    Let’s return to the sample class written earlier, and see how this function can be used for writing defensive code:

    class FileReader{
      var $file;
      var $fileDir='fileDir/';
      function FileReader($file){
        if(!file_exists("{$this->fileDir}{$file}.php")){
          trigger_error('File '.$file.' not found',E_USER_WARNING);
        }
        $this->file=$file;
      }
      function getContent(){
        if(!$content=file_get_contents("{$this->fileDir}{$this->file}.php")){
          trigger_error("Unable to read file contents",E_USER_WARNING);
        }
        return $content;
      }
    }

    As seen above, I’ve included a couple of “trigger_error()” functions, right at the places where the class could raise potential errors. According to this rewritten class, a file reader object might be instantiated like this:

    // instantiate FileReader object
    $fr=new FileReader('inexistent_file');
    // echo file content
    echo $fr->getContent();

    And the resulting output would be as follows:

    Notice: File inexistent_file not found in path/to/file
    Warning: file_get_contents(fileDir/inexistent_file.php): failed to open stream: No such file or directory in path/to/file
    Notice: Unable to read file contents in path/to/file

    In this case, the “trigger_error()” function will display some notices and warnings when a specific error has occurred, but in all cases the execution of the program won’t be stopped, since I passed into the function a non-fatal error flag (E_USER_WARNING). As you may have guessed, this error mechanism isn’t very useful when used alone. After all, what’s the point of having a bunch of non-fatal errors, if they’re not processed in a more helpful way?

    The real power of the “trigger_error()” function is unleashed when used in conjunction with the “set_error_handler()” function. As you probably know, this function allows us to specify the name of an error handling function, and whenever an error is triggered, program flow will be moved to the specified function.

    Certainly, the “trigger_error()/set_error_handler()” combination is very handy for delegating error handling toward a delineated section within an application. To demonstrate its functionality, I’ll rewrite the sample class, this time by specifying a callback function for “set_error_handler()”. Take a look:

    class FileReader{
      var $file;
      var $fileDir='fileDir/';
      function FileReader($file){
        if(!file_exists("{$this->fileDir}{$file}.php")){
          trigger_error('File '.$file.' not found',E_USER_WARNING);
        }
        $this->file=$file;
      }
      function getContent(){
        if(!$content=file_get_contents("{$this->fileDir}{$this->file}.php")){
          trigger_error("Unable to read file contents",E_USER_WARNING);
        }
        return $content;
      }
    }
    // define error handling function

    function fileErrorHandler($errnum,$errmsg,$file,$lineno){
      if($errnum==E_USER_WARNING){
        echo 'Error: '.$errmsg.'<br />File: '.$file.'<br />Line: '.$lineno;
        exit();
      }
    }

    As shown above, I’ve defined the “fileErrorHandler()” function, in order to trap raised errors, and incidentally obtain more specific information about the error that occurred. In this example, the function has been written to display only information on E_USER_WARNING errors, by displaying the message passed in through each “trigger_error()” function, along with the filename and line number at which the error originally occurred. With such a useful error handler, let’s see the output for the improved version of the sample script:

    // define error handling function
    set_error_handler('fileErrorHandler');
    // instantiate FileReader object
    $fr=new FileReader('inexistent_file');
    // echo file content
    echo $fr->getContent();

    Error: File inexistent_file not found
    File: path/to/file/exception.php
    Line: 6

    Now, things are more interesting. Notice how program flow was transferred to the “fileErrorHandler()” function, when the first “trigger_error()” function raised an error condition. Additionally, I received slightly more detailed information on the error itself, since the script's output included the type of error, file and line number where the error took place. This alone gives us a considerable improvement on setting up error handlers, because by defining a callback function, it’s possible to build in a centralized error handling mechanism and liberate application code from manipulating potentially conflictive conditions.

    In most cases, the “trigger_error()”/set_error_handler()” combination can be successfully implemented, in order to work either with procedural programs or with object-based applications. Particularly in object-oriented environments, one common approach consists of developing a class (or a set of classes), which are responsible for handling all the errors raised during the execution of an program.

    So, taking into account that object-based error manipulation is relevant during the development of an application, it’s worthwhile to take a brief look at the popular PEAR error object, so you can have a clear idea of how it works with the previous “FileReader” class.

    More PHP Articles
    More By Alejandro Gervasio


       · This first article demonstrates some of the most common approaches for handling...
       · I had expected something about the try catch throw statements as well...Aren't...
       · Hello,Thank you for commenting on my article. Regarding your question, I covered...
       · Boolean flags are a technique I frequently use specifically in writing APIs. I...
       · Hello Lux,Thank you for your feedback on this article. I saw your method about...
     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT