CakePHP - 錯誤與異常處理



為了系統的平穩執行,必須有效地處理系統故障。CakePHP 帶有預設的錯誤捕獲功能,會在錯誤發生時列印和記錄錯誤。此相同的錯誤處理程式用於捕獲**異常**。

當 debug 為 true 時,錯誤處理程式會顯示錯誤,當 debug 為 false 時,會記錄錯誤。CakePHP 擁有許多異常類,內建的異常處理機制將捕獲任何未捕獲的異常並呈現有用的頁面。

錯誤和異常配置

錯誤和異常可以在檔案**config\app.php**中配置。錯誤處理接受一些選項,允許您為您的應用程式定製錯誤處理:

選項 資料型別 描述
errorLevel int

您感興趣的捕獲錯誤級別。使用內建的 php 錯誤常量和位掩碼來選擇您感興趣的錯誤級別。

trace bool

在日誌檔案中包含錯誤的堆疊跟蹤。堆疊跟蹤將在每個錯誤之後包含在日誌中。這有助於查詢錯誤發生的位置/時間。

exceptionRenderer string

負責呈現未捕獲異常的類。如果您選擇**自定義**類,則應將該類的檔案放在**src/Error**中。此類需要實現**render()**方法。

log bool

為 true 時,異常及其堆疊跟蹤將記錄到**Cake\Log\Log**。

skipLog array

不應該記錄的異常類名陣列。這對於移除**NotFoundExceptions**或其他常見但無趣的日誌訊息很有用。

extraFatalErrorMemory int

遇到致命錯誤時,設定為增加記憶體限制的兆位元組數。這允許有足夠的餘地來完成日誌記錄或錯誤處理。

示例

按照以下程式碼所示修改**config/routes.php**檔案。

config/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('/exception/:arg1/:arg2',
      ['controller'=>'Exps','action'=>'index'],
      ['pass' => ['arg1', 'arg2']]);
   $builder->fallbacks();
});

在**src/Controller/ExpsController.php**處建立**ExpsController.php**檔案。將以下程式碼複製到控制器檔案中。

src/Controller/ExpsController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\Core\Exception\Exception;
   class ExpsController extends AppController {
      public function index($arg1,$arg2) {
         try{
            $this->set('argument1',$arg1);
            $this->set('argument2',$arg2);
            if(($arg1 > 1 || $arg1 > 10) || ($arg2 < 1 || $arg2 > 10))
               throw new Exception("One of the number is out of range [1-10].");
         } catch(\Exception $ex){
            echo $ex->getMessage();
         }
      }
   }
?>

在**src/Template**處建立一個目錄**Exps**,並在該目錄下建立一個名為 index.php 的**View**檔案。將以下程式碼複製到該檔案中。

src/Template/Exps/index.php

This is CakePHP tutorial and this is an example of Passed arguments.
Argument-1: <?=$argument1?><br/> Argument-2: <?=$argument2?><br/>

透過訪問以下 URL 來執行上述示例。

https:///cakephp4/exception/5/0

輸出

執行後,您將收到以下輸出。

Arguments
廣告
© . All rights reserved.