Yii: Catching all exceptions for a specific controller

yii
Eugene picture Eugene · Jun 20, 2012 · Viewed 14k times · Source

I am working on a project which includes a REST API component. I have a controller dedicated to handling all of the REST API calls.

Is there any way to catch all exceptions for that specific controller so that I can take a different action for those exceptions than the rest of the application's controllers?

IE: I'd like to respond with either an XML/JSON formatted API response that contains the exception message, rather than the default system view/stack trace (which isn't really useful in an API context). Would prefer not having to wrap every method call in the controller in its own try/catch.

Thanks for any advice in advance.

Answer

medve picture medve · Jul 11, 2012

You can completely bypass Yii's default error displaying mechanism by registering onError and onException event listeners.

Example:

class ApiController extends CController
{
  public function init()
  {
    parent::init();

    Yii::app()->attachEventHandler('onError',array($this,'handleError'));
    Yii::app()->attachEventHandler('onException',array($this,'handleError'));
  }

  public function handleError(CEvent $event)
  {        
    if ($event instanceof CExceptionEvent)
    {
      // handle exception
      // ...
    }
    elseif($event instanceof CErrorEvent)
    {
      // handle error
      // ...
    }

    $event->handled = TRUE;
  }

  // ...
}