Home arrow PHP arrow Page 3 - Error Handling in PHP: Coding Defensively

Triggering errors: more efficient error handling with the “trigger_error()” function - PHP

As with any programming language, when you code in PHP, it helps immensely if you set up your applications to handle errors gracefully. This article explores some of the most common error checking methods available in PHP, and provides hands-on examples that use different error handling methods.

TABLE OF CONTENTS:
  1. Error Handling in PHP: Coding Defensively
  2. Killing your scripts: basic error handling with the “die()” statement
  3. Triggering errors: more efficient error handling with the “trigger_error()” function
  4. The PEAR way: looking at the PEAR_Error object
  5. True and false: handling errors with Boolean flags
By: Alejandro Gervasio
Rating: starstarstarstarstar / 52
January 11, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: