2016-04-15 19 views
2

私はCakephpでjson形式をレンダリングするAPIを扱っています。私が持っているAppController.phpで :メインコントローラに続行せずにbeforefilterの続行を停止するにはどうすればよいですか?

public function beforeFilter() { 
    $this->RequestHandler->renderAs($this, 'json'); 

    if($this->checkValid()) { 
    $this->displayError(); 
    } 
} 
public function displayError() { 
    $this->set([ 
    'result'  => "error", 
    '_serialize' => 'result', 
    ]); 
    $this->response->send(); 
    $this->_stop(); 
} 

しかし、それは何も表示されません。ただし、停止して表示せずに正常に実行された場合は、

$this->set([ 
'result'  => "error", 
'_serialize' => 'result', 
]); 

が表示されます。

+0

応答を表示するために終了する前にビューをレンダリングする必要がありますが、確実ではありません。 –

+1

beforeFilterはコントローラの動作を停止させず、$ this-> autoRender = false;コントローラーの動作が自動的に表示されなくなります。 – HelloSpeakman

+0

私は、感謝@HelloSpeakmanを参照してください。 URLを変更せずに別のコントローラにリダイレクトする方法はありますか? – ralphjason

答えて

1

カスタムjson exceptionRendererを使用して例外を使用します。

if($this->checkValid()) { 
    throw new BadRequestException('invalid request'); 
} 

あなたのアプリ/コンフィグ/ bootstrap.phpの中で、これを含めることにより、カスタム例外ハンドラを追加します。

/** 
* Custom Exception Handler 
*/ 
App::uses('AppExceptionHandler', 'Lib'); 

Configure::write('Exception.handler', 'AppExceptionHandler::handleException'); 

はその後AppExceptionHandler.php

この名前のあなたのapp/Libフォルダに新しいカスタム例外ハンドラを作成しますファイルは次のように表示されます。

<?php 

App::uses('CakeResponse', 'Network'); 
App::uses('Controller', 'Controller'); 

class AppExceptionHandler 
{ 

    /* 
    * @return json A json string of the error. 
    */ 
    public static function handleException($exception) 
    { 
     $response = new CakeResponse(); 
     $response->statusCode($exception->getCode()); 
     $response->type('json'); 
     $response->send(); 
     echo json_encode(array(
      'status' => 'error', 
      'code' => $exception->getCode(), 
      'data' => array(
       'message' => $exception->getMessage() 
      ) 
     )); 
    } 
} 
+0

ありがとう!私はこれを考えます。 – ralphjason

関連する問題