php - 如何在不继续到主 Controller 的情况下停止在 beforefilter 中继续?

标签 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() {
  $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.phpapp/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/

相关文章:

JavaScript 不更新表单操作

c++ - KDB C++ API : creating a list of strings

PHP Json 不一致

php - Swift httppost 数据未插入到 MySQL 数据库

c++ - 使用 "JSON for Modern C++"库检测整数不适合指定类型?

javascript - 使用 JS 定位类名迭代

ajax - 有什么不应该进入 HTTP header 的指南吗?

api - 概念:API级别测试

php - 更改 Yii 2 中邮件的默认查看路径?

php - 在 PHP 中处理全局变量的最有效方法是什么?