Zend Framework + Whoops (php errror for cool kids)

Posted by Peter
tags: php zend framework

In Zend Framework you can easily set a controller and action for error handling. In fact there is always default set for you. There is also default template. But what if you’d like to use something more sophisticated, let’s say.. nicer looking or better displaying error stack trace, which obviously helps a lot while debugging?

My suggestion is to use Whoops, an open source library enabling great looking and very intuitive error displaying in any PHP application. Whoops author prepared support for Zend Framework 2, Silex and more, but unfortunately there is no ready solution for Zend Framework 1 and this is what I’ll try to do in this article.

First of all you’ll need a way to enable it. You can include appropriate classes in index.php or some other place. I, on the other hand, prefer Composer, an open source package manager for PHP. I won’t go into details in here on how to set up Composer autoloading - you can see one way of doing in my previous article or use your own way, whichever you prefer.

To include Whoops in Composer, add this to “require” section in composer.json:

1
2
3
4
5
{
  "require": {
    "filp/whoops": "1.*"
  }
}

And install it with:

1
composer install

Now it is time to init Whoops  and register it as a default error handler. I do it in main bootstrap like this:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
protected function _initWhoops()
{
    // creating new Whoops object
    $whoops = new Whoops\Run();

    // adding an error handler, pretty one ;)
    $whoops->pushHandler(new Whoops\Handler\PrettyPageHandler());

    // and now final touch: setting Whoops as default error handler
    $whoops->register();
}

One other thing which I had to do was to force Zend Framework to ignore all errors and let Whoops handle them. In fact this works for every other error handler. In method described before add one line, just before everything else:

1
2
<?php
Zend_Controller_Front::getInstance()->throwExceptions(true);

All together should look something like that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
protected function _initWhoops()
{
    // this line forces Zend Framework to throw Exceptions as they are and letting us handle them
    Zend_Controller_Front::getInstance()->throwExceptions(true);

    // creating new Whoops object
    $whoops = new Whoops\Run();

    // adding an error handler, pretty one ;)
    $whoops->pushHandler(new Whoops\Handler\PrettyPageHandler());

    // and now final touch: setting Whoops as default error handler
    $whoops->register();
}

Basically that’s it. Now Whoops should intercept all errors and show them in fancy way :)