Make your Zend Framework Error Controller handle PHP errors

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.

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'));
    }
}
    

3 comments

  1. Simple and does exactly what I need- transform generic errors into exceptions that are then handled by my ErrorController.

    One comment- perhaps the Exception should use $errno as the 2nd parameter.

  2. Great example, thanks! I’m wandering though how we can use the the static call to

    MyApp_Error_Handler::set();

    when __initAutoload() hasnt been called yet.

    Am I missing something?

  3. i need a sample process of zend framework through a code i am begginer to zend i need it for my project i refer many site but its waste of time to me …………..

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.