作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用在 Cakephp 中呈现 json 格式的 API。在 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');
然后在名为 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()
)
));
}
}
关于php - 如何在不继续到主 Controller 的情况下停止在 beforefilter 中继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36641201/
我是一名优秀的程序员,十分优秀!