I'm working with APIs that renders json format in Cakephp.
In the AppController.php I have:
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();
}
But it doesn't display anything. Though, if it is run normally without stopping and displaying with:
$this->set([
'result' => "error",
'_serialize' => 'result',
]);
is displaying good.
I would look at using Exceptions with a custom json exceptionRenderer.
if($this->checkValid()) {
throw new BadRequestException('invalid request');
}
add a custom exception handler by including this in your app/Config/bootstrap.php:
/**
* Custom Exception Handler
*/
App::uses('AppExceptionHandler', 'Lib');
Configure::write('Exception.handler', 'AppExceptionHandler::handleException');
then create a new custom exception handler in your app/Lib folder named AppExceptionHandler.php
this file can look something like this:
<?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()
)
));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With