Php 如何停止在beforefilter中继续而不继续主控制器?
我正在使用用Cakephp呈现json格式的API。 在Php 如何停止在beforefilter中继续而不继续主控制器?,php,json,api,cakephp,serialization,Php,Json,Api,Cakephp,Serialization,我正在使用用Cakephp呈现json格式的API。 在AppController.php中,我有: public function beforeFilter() { $this->RequestHandler->renderAs($this, 'json'); if($this->checkValid()) { $this->displayError(); } } public function displayError() { $th
AppController.php
中,我有:
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',
]);
显示良好。我将研究如何将异常与自定义json exceptionRenderer一起使用
if($this->checkValid()) {
throw new BadRequestException('invalid request');
}
在app/Config/bootstrap.php中添加自定义异常处理程序:
/**
* Custom Exception Handler
*/
App::uses('AppExceptionHandler', 'Lib');
Configure::write('Exception.handler', 'AppExceptionHandler::handleException');
然后在app/Lib
文件夹中创建一个名为AppExceptionHandler.php
此文件可以如下所示:
<?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()
)
));
}
}
我在某个地方读到,您需要在退出前呈现视图以显示响应,但不确定..在筛选器不会停止正在运行的控制器操作之前,您可以尝试$this->autoRender=false;这将停止控制器自动呈现视图的操作。我明白了,谢谢@HelloSpeakman。有没有办法在不更改URL的情况下重定向到另一个控制器?谢谢!我会考虑这个。