Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop continuing in beforefilter without continuing to the main controller?

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.

like image 922
ralphjason Avatar asked Jan 21 '26 12:01

ralphjason


1 Answers

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()
            )
        ));
    }
}
like image 171
Jason Joslin Avatar answered Jan 23 '26 01:01

Jason Joslin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!