Yii: Catching all exceptions for a specific controller

前端 未结 5 1757
日久生厌
日久生厌 2020-12-25 15:08

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 exc

相关标签:
5条回答
  • 2020-12-25 15:15

    You can write your own actionError() function per controller. There are several ways of doing that described here

    0 讨论(0)
  • 2020-12-25 15:21

    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;
      }
    
      // ...
    }
    
    0 讨论(0)
  • 2020-12-25 15:24

    I wasn't able to attach events in controller, and I did it by redefinition CWebApplication class:

    class WebApplication extends CWebApplication
    {
    protected function init()
    {
        parent::init();
    
        Yii::app()->attachEventHandler('onError',array($this, 'handleApiError'));
        Yii::app()->attachEventHandler('onException',array($this, 'handleApiError'));
    }
    
    /**
     * Error handler
     * @param CEvent $event
     */
    public function handleApiError(CEvent $event)
    {
        $statusCode = 500;
    
        if($event instanceof CExceptionEvent)
        {
            $statusCode = $event->exception->statusCode;
            $body = array(
                'code' => $event->exception->getCode(),
                'message' => $event->exception->getMessage(),
                'file' => YII_DEBUG ? $event->exception->getFile() : '*',
                'line' => YII_DEBUG ? $event->exception->getLine() : '*'
            );
        }
        else
        {
            $body = array(
                'code' => $event->code,
                'message' => $event->message,
                'file' => YII_DEBUG ? $event->file : '*',
                'line' => YII_DEBUG ? $event->line : '*'
            );
        }
    
        $event->handled = true;
    
        ApiHelper::instance()->sendResponse($statusCode, $body);
    }
    }
    

    In index.php:

    require_once(dirname(__FILE__) . '/protected/components/WebApplication.php');
    Yii::createApplication('WebApplication', $config)->run();
    
    0 讨论(0)
  • 2020-12-25 15:26

    I'm using the following Base controller for an API, it's not stateless API, mind you, but it can serve just aswell.

    class BaseJSONController extends CController{

            public $data = array();
    
            public $layout;
    
            public function filters()
            {
                    return array('mainLoop');
            }
    
            /**
             * it all starts here
             * @param unknown_type $filterChain
             */
            public function filterMainLoop($filterChain){
                    $this->data['Success'] = true;
                    $this->data['ReturnMessage'] = "";
                    $this->data['ReturnCode'] = 0;
                    try{
                            $filterChain->run();
    
                    }catch (Exception $e){
                            $this->data['Success'] = false;
                            $this->data['ReturnMessage'] = $e->getMessage();
                            $this->data['ReturnCode'] = $e->getCode(); 
                    }
    
                    echo json_encode($this->data);
            }
    }
    

    You could also catch dbException and email those, as they're somewhat critical and can show underlying problem in the code/db design.

    0 讨论(0)
  • 2020-12-25 15:26

    Add this to your controller:

    Yii::app()->setComponents(array(
        'errorHandler'=>array(
            'errorAction'=>'error/error'
        )
    ));
    
    0 讨论(0)
提交回复
热议问题