18

REST API コンポーネントを含むプロジェクトに取り組んでいます。すべての REST API 呼び出しを処理する専用のコントローラーがあります。

その特定のコントローラーのすべての例外をキャッチして、それらの例外に対してアプリケーションの残りのコントローラーとは異なるアクションを実行できるようにする方法はありますか?

IE: デフォルトのシステム ビュー/スタック トレース (API コンテキストではあまり役に立ちません) ではなく、例外メッセージを含む XML/JSON 形式の API 応答で応答したいと考えています。コントローラー内のすべてのメソッド呼び出しを独自の try/catch でラップする必要はありません。

事前にアドバイスをありがとう。

4

5 に答える 5

38

onErrorおよびonExceptionイベントリスナーを登録することにより、Yii のデフォルトのエラー表示メカニズムを完全にバイパスできます。

例:

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

  // ...
}
于 2012-07-11T11:50:16.797 に答える
9

コントローラーにイベントをアタッチできませんでした。CWebApplication クラスを再定義して実行しました。

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

index.php で:

require_once(dirname(__FILE__) . '/protected/components/WebApplication.php');
Yii::createApplication('WebApplication', $config)->run();
于 2013-01-16T09:16:34.543 に答える
3

コントローラごとに独自のactionError()関数を作成できます。ここで説明されていることを行うにはいくつかの方法があります

于 2012-06-21T00:51:25.570 に答える
1

私は API に次の Base コントローラーを使用しています。これはステートレス API ではありませんが、同様に機能します。

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

また、dbException をキャッチして電子メールで送信することもできます。これらはやや重要であり、コード/データベース設計の根本的な問題を示す可能性があるためです。

于 2013-01-16T16:31:14.410 に答える
0

これをコントローラーに追加します。

Yii::app()->setComponents(array(
    'errorHandler'=>array(
        'errorAction'=>'error/error'
    )
));
于 2014-06-26T14:00:27.477 に答える