Since PHP 5 it's possible to handle errors outside the running code with the built in Exception class. By means of throwing an exception and catching it in a special block all the error handling is in one distinct place. It's even possible to give each exception a specific number to identify the error. If an exception is thrown the script jumps immediately to the catch block (in a development environment we would want to see a description of the problem but in a production environment some error view could be rendered). Use exceptions (instead of custom input validation in a model) if a wrong data type may cause the application to behave in an unpredicted way, or not at all.
Once the exception is caught it's possible to extract information about the error with several built in methods:


<?php
        
class Products{

            protected 
$_title;
            protected 
$_category;
            protected 
$_price;

            public function 
__construct($title$category$price){
                if(
$price 0){
                    throw new 
Exception("Price must be a positive number"1);
                }
                
$this->_title $title;
                
$this->_category $category;
                
$this->_price $price;
            }

            public function 
getPrice(){
                return 
$this->_price;
            }
        }


        try{
            
$product = new Products("Title""Category", -45);
            echo 
$product->getPrice();
        }
        catch(
Exception $e){
            echo 
"Caught exception Message: "$e->getMessage()."<br/>"// Caught exception Message: Price must be a positive number
            
echo "Caught exception Code: ".  $e->getCode()."<br/>"// Caught exception Code: 1
            
echo "Caught exception File: "$e->getFile()."<br/>"// Caught exception File: wwwdocs/example/app/products.php
            
echo "Caught exception Line: ".  $e->getLine()."<br/>"// 10
            
echo "Caught exception Trace (array): <pre>";
                
print_r($e->getTrace());  // array with file, line, function, class, type, args
            
echo "</pre><br/>";
            echo 
"Caught exception Trace as string: ".  $e->getTraceAsString()."<br/>";
            echo 
"Caught exception using echo: ".  $e."<br/>"// combines getMessage() and getTraceAsString()
        
}

?>


comments powered by Disqus