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