Kohana workaround to side-step debug information in production

Kohana provides a nice exception handler (and an error handler that transforms errors into exceptions using PHP’s ErrorException class) which displays all kind of useful information in a development environment.
In addition to the error/exception related information, you also get environment-specific information that can help you troubleshoot your application : path of your application, php extensions, server software, and so on. Of course, it is always bad to display this kind of information on a live website.

However, while working with Gilbert on the recently launched Paris Photo site, we encountered an odd Kohana behavior:  uncaught exceptions thrown within a view were being displayed with stack trace and environment debug info no matter what the errors settings were when Kohana::init was called. That means, even in production.

The issue

If there’s an error somewhere in a view and an exception is thrown, a Kohana error with debug information will be displayed (even if you set errors to false in the bootstrap) in the following situation : the View object was directly echoed (meaning View::__toString was called). Even if it looks like we’re supposed to be able to directly echo a View instance, this shouldn’t be used at any time.

The Kohana documentation doesn’t warn you against the fact that you can’t throw an exception in a PHP __toString magic method (it’s apparently “pretty hard” to implement in the Zend Engine) so the Kohana developers simply chose to display the Kohana error with debug information no matter the value of Kohana::$errors.

Workaround

Always use echo aView->render() rather than echo aView or echo View::factory('my/view')

To help you and your team to avoid reproducing the same error, I recommend to extend Kohana::View in application and add the following in application/classes/View.php :

<?php defined('SYSPATH') OR die('No direct script access.');

class View extends Kohana_View {

  public function __toString()
  {
    restore_error_handler();
    trigger_error('For safety reasons, View::__toString should not be used. Please read http://opticalcortex.com/kohana-workaround-not-to-get-debug-information-in-production for more information.', E_USER_ERROR);
  }
}

I can’t currently post a ticket to the Kohana bug tracker as it seems down since yesterday. This post will soon be edited with the ticket address.