為使系統(tǒng)平穩(wěn)的運行,系統(tǒng)一旦出現(xiàn)故障就必須被有效的處理掉。CakePHP默認(rèn)附帶錯誤捕獲功能,當(dāng)錯誤發(fā)生的時候,就會打印并記錄這些錯誤。這個錯誤捕獲程序也被用來捕獲異常,當(dāng)debug為true的時候顯示錯誤,當(dāng)debug為false的時候記錄錯誤。CakePHP擁有數(shù)量龐大的異常類和內(nèi)置的異常處理程序,會捕獲任何異常并顯示一個帶有有用信息的頁面。
錯誤和異??梢栽?strong>config\app.php文件中進(jìn)行配置。以下選項可以讓讓您定制應(yīng)用程序的錯誤處理程序-
選項 | 數(shù)據(jù)類型 | 描述 |
---|---|---|
errorLevel | int | 要捕獲的錯誤級別。 使用內(nèi)置的PHP錯誤常量和位掩碼來選擇你要捕獲的錯誤的級別。 |
trace | bool | 是否在日志文件中為錯誤包含堆棧跟蹤。 堆棧跟蹤將包含在日志中的每個錯誤后,有助于查找錯誤在何時何處發(fā)生。 |
exceptionRenderer | string | 該類負(fù)責(zé)呈現(xiàn)未捕獲的異常。 如果您選擇自定義類,你應(yīng)該把該類的文件放到src/Error目錄下。這個類需要實現(xiàn)一個render()方法。 |
log | bool | 如果為true,異常+它們的堆棧跟蹤將被記錄到Cake\Log\Log文件中 。 |
skipLog | array | 一個存儲不需要記錄的異常類名的數(shù)組。 對過濾NotFoundExceptions或其他常見的,但不感興趣的日志非常有用。 |
extraFatalErrorMemory | int | 為致命錯誤發(fā)生時設(shè)置一個值(MB)來增加內(nèi)存。以保證可以完成日志記錄或錯誤處理。 |
修改config/routes.php文件如下。
config/routes.php文件
<?php use CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass('DashedRoute'); Router::scope('/', function (RouteBuilder $routes) { $routes->connect('/exception/:arg1/:arg2',[ 'controller'=>'Exps','action'=>'index'],['pass' => ['arg1', 'arg2']]); $routes->fallbacks('DashedRoute'); }); Plugin::routes();
在src/Controller/目錄下創(chuàng)建ExpsController.php文件。復(fù)制以下代碼代碼至其中。
src/Controller/ExpsController.php
<?php namespace AppController; use AppControllerAppController; use CakeCoreExceptionException; 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目錄下創(chuàng)建一個名為Exps目錄,并在此Exps下創(chuàng)建一個名為index.ctp的視圖文件。復(fù)制以下代碼至其中。
src/Template/Exps/index.ctp
This is CakePHP tutorial and this is an example of Passed arguments. Argument-1: <?=$argument1?> Argument-2: <?=$argument2?>
通過訪問以下網(wǎng)址執(zhí)行上面的例子。
http://localhost:85/CakePHP/exception/5/0
執(zhí)行以上程序,您會看到如下頁面。
更多建議: