我正在使用在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',
]);
表现良好。
我会考虑将Exceptions与自定义json exceptionRenderer一起使用。
if($this->checkValid()) {
throw new BadRequestException('invalid request');
}
添加一个自定义异常处理程序,将其包含在您的app/Config/bootstrap.hp:中
/**
* 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()
)
));
}
}