簡體   English   中英

Cakephp:如果缺少操作,如何處理異常

[英]Cakephp: How to handle exception if action is missing

我正在開發Cakephp中的Api。 如果android app調用錯誤的函數或錯誤的控制器,我需要處理異常。 我需要知道如何處理它並將json中的響應返回到我的Android應用程序。 我的意思是我知道我可以在我的beforefilter函數中寫一些東西,因為這個函數將首先執行但是我不知道如何首先捕獲異常或者如何檢測事件。 通過谷歌搜索我找到了一些解決方案,但它仍然無法正常工作。 這是我嘗試過的代碼。

應用程序/庫/ AppErrorHandler.php

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

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

在bootstrap.php中

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

關於異常我在Api中沒有做任何事情。 如果我還要在Api課程中編寫一些代碼,請告訴我

您正在為自定義ExceptionHandler擴展ExceptionRenderer,這是正確的方法。 現在你試圖覆蓋方法handleException ,它基本上不存在於baseClass中。 這樣做是錯的..

現在為您的解決方案:您需要覆蓋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中,您將找到處理默認異常的文件。 在exceptions.php中,您將找到拋出或拋出的不同錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM