2016-04-15 69 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