Cakephp:如果缺少操作,如何处理异常


Cakephp: How to handle exception if action is missing

我正在用Cakephp开发一个API。如果安卓应用程序调用错误的功能或错误的控制器,我需要处理异常。我需要知道如何处理它并以 json 格式将响应返回到我的 android 应用程序。我的意思是我知道我可以在我的 beforefilter 函数中写一些东西,因为这个函数将首先执行,但我不知道如何首先捕获异常或如何检测事件。通过谷歌搜索,我得出了一些解决方案,但它仍然不起作用。这是我在下面尝试过的代码。

App/Lib/AppErrorHandler.php

 class AppErrorHandler extends ExceptionRenderer{
  public static function handleException($error) {
        if ($error instanceof MissingActionException) {
          echo "incorrect controller action name";
            exit;
        }
    }
}
?>

在引导中.php

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

我没有在我的 API 中做任何关于异常的事情。如果我也必须在 Api 类中编写一些代码,请告诉我

您正在为自定义 ExceptionHandler 扩展 ExceptionRenderer,这是正确的方法。现在你正在尝试覆盖方法句柄异常,它基本上不存在在基类中。所以这样做是错误的。

现在为您的解决方案:你需要从 ExceptionRenderer 类中覆盖函数 render()。您的操作方法如下:

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:在lib/Cake/Error中,您将找到处理默认异常的文件。在异常中.php您会发现抛出或可以抛出的不同错误。