简体   繁体   中英

Cakephp: How to handle exception if action is missing

I am developing an Api in Cakephp. I need to handle the exception if android app calls wrong function or wrong controller. I need to know how can I can handle that and return the response in json to my android app. I mean I know I can write something in my beforefilter function because this function will execute first But I don't know how I can catch first the exception or how can I detect the event. By Googling I come to some solution but still it is not working. Here is my code below which I have tried.

App/Lib/AppErrorHandler.php

 class AppErrorHandler extends ExceptionRenderer{
  public static function handleException($error) {
        if ($error instanceof MissingActionException) {

          echo "incorrect controller action name";
            exit;
        }
    }
}
?>

in bootstrap.php

App::uses('AppErrorHandler', 'Lib');

I didn't do anything in my Api regarding exception. Please let me know if I have to write some code in Api class too

You are extending ExceptionRenderer for your custom ExceptionHandler, which is the right way. Now you are trying to override method handleException which basically is not present in the baseClass. So Its wrong to do that..

Now for your solution: You need to override function render() from ExceptionRenderer class. The way you do it is below:

class AppErrorHandler extends ExceptionRenderer{
    public function render() {       
        if ($this->method) {            
            if($this->error instanceof MissingActionException) {
                // echo here whatever you want..
            }
            call_user_func_array(array($this, $this->method), array($this->error));    
            // this line is required to render the normal page as per the error code.. 400 or 500 or similar..
        }
    }
}

PS: in lib/Cake/Error you will find the files which handle the default exceptions. Here in exceptions.php you will find the different errors which are thrown or can be thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM