gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:00:07 24 4
gpt4 key购买 nike

我正在使用在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com