The Zend Framework Quick Start tutorial comes with a great example of the type of error handling Zend Framework can do. Any exception that is thrown almost anywhere in your application is caught and handled by the Error Controller. This allows for very customized development and/or user error messages. But what about generic PHP errors? What about PHP notices? It’s really annoying to see a white screen with a single PHP error after you’ve spent so long trying to get your pretty Error Controller handled errors looking so nice.

PHP has a nifty function called set_error_handler which allows you to, well, set the error handler. You provide it a callback function and it calls your function when something bad happens. While it obviously can’t catch all PHP errors, it does a pretty good job of catching most of the little annoying ones.

Below is a way to set your ErrorController as the PHP error handler.

[ad name=”Google Adsense 468×60″]

Add the following method to your Bootstrap.php class.

public function __construct($application) {
    parent::__construct($application);
    MyApp_Error_Handler::set();
}

Add this code to a file called library/MyApp/Error/Handler.php

class MyApp_Error_Handler {
    public static function handle($errno, $errstr, $errfile, $errline) 
    {
        if (!error_reporting()) return;
        throw new Exception($errstr . " in $errfile:$errline". $errno);
    }
        
    public static function set()
    {
        set_error_handler(array(__CLASS__, 'handle'));
    }
}
    

Share