Manuel Pear

Using PEAR_Exception for advanced error handling in PHP 5+

Using PEAR_Exception for advanced error handling in PHP 5+  --  Using PEAR_Exception

Synopsis

Introduction to the usage of PEAR_Exception

Introduction

This class is available as part of the PEAR package. Features include:

  • Nestable exceptions (

    1. <?php throw new PEAR_Exception($msg, $prev_exception);  
    2. ?> 
    )
  • Subject/Observer pattern, triggered when an exception is instantiated

  • Clear, detailed and attractively formatted error messages

  • Extra context information available compared to built-in Exception. For instance, a cause of the exception (PEAR_Error/PEAR_ErrorStack/another Exception).

  • Exception cause can be a PEAR_Error object, PEAR_Exception object or an array of mixed PEAR_Exceptions/PEAR_ErrorStack warnings

  • callbacks for specific exception classes and their children

Usage example:

  1. <?php
  2. require_once 'PEAR/Exception.php';  
  3.  
  4. class Test { 
  5.       function foo() { 
  6.             throw new PEAR_Exception('Error Message', ERROR_CODE); 
  7.    }  
  8. }  
  9.  
  10. function myLogger($pear_exception) { 
  11.    echo $pear_exception->getMessage();  
  12. }  
  13. // each time a exception is thrown the 'myLogger' will be called
  14. // (its use is completely optional)
  15. PEAR_Exception::addObserver('myLogger');  
  16. $test = new Test;  
  17. try { 
  18.    $test->foo();  
  19. } catch (PEAR_Exception $e) { 
  20.    print $e;  
  21. }  
  22.  
  23. ?> 

API documentation is documented in the documentation for the PEAR package generated by phpDocumentor. The class is very simple, examine the source in the PEAR package to get a better idea of how it works.


Remonter Remonter
L'éditeur javascript - CSS - Gentoo - Tutoriaux PHP - Tutoriels PHP - Bretagne - php - Moto - Kit graphique