Yii中包括一個內置的錯誤處理程式。Yii錯誤處理程式將執行以下操作 -
-
轉換所有非致命PHP錯誤到可捕獲異常
-
顯示帶有詳細的調用堆疊的所有錯誤和異常
-
支持不同的錯誤格式
-
支持使用一個控制器動作來顯示錯誤
要禁用錯誤處理,應該在入口腳本中定義 YII_ENABLE_ERROR_HANDLER 常量為 false 。
錯誤處理程式被註冊為一個應用程式組件。
步驟1 - 可以通過以下方式對其進行配置,代碼如下所示:
return [ 'components' => [ 'errorHandler' => [ 'maxSourceLines' => 10, ], ], ];
上述配置設置以便顯示源代碼的數量為 10 行 。錯誤處理程式將所有非致命PHP錯誤到可捕獲異常。
第2步 - 添加 actionShowError() 方法到 SiteController。
public function actionShowError() { try { 5/0; } catch (ErrorException $e) { Yii::warning("Ooops...division by zero."); } // execution continues... }
第3步 - 打開URL http://localhost:8080/index.php?r=site/show-error 會看到一個警告消息。

如果想顯示給用戶說明他的請求是無效的,可以拋出 yii\web\NotFoundHttpException 。
步驟4 - 修改 actionShowError()函數(在 SiteController 中)。
public function actionShowError() { throw new NotFoundHttpException("Something unexpected happened"); }
當 YII_DEBUG 常量設置為 true ,錯誤處理程式將顯示詳細的調用堆疊的錯誤。
當常量常量設置為 false ,則僅顯示該錯誤消息。默認情況下,錯誤處理程式使用這些視圖顯示錯誤
-
@yii/views/errorHandler/exception.php − 當調用堆疊資訊顯示錯誤時視圖檔應該會被使用。
-
@yii/views/errorHandler/error.php − 當在不調用堆疊資訊顯示錯誤時視圖檔被使用。
也可以使用指定錯誤處理的動作,以自定義顯示錯誤。
第6步 - 在 config/web.php 檔修改 ErrorHandler 應用程式組件。
<?php $params = require(__DIR__ . '/params.php'); $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'components' => [ 'request' => [ // !!! insert a secret key in the following (if it is empty) - this //is required by cookie validation 'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO', ], 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, ], 'errorHandler' => [ 'errorAction' => 'site/error', ], //other components... 'db' => require(__DIR__ . '/db.php'), ], 'modules' => [ 'hello' => [ 'class' => 'app\modules\hello\Hello', ], ], 'params' => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for 'dev' environment $config['bootstrap'][] = 'debug'; $config['modules']['debug'] = [ 'class' => 'yii\debug\Module', ]; $config['bootstrap'][] = 'gii'; $config['modules']['gii'] = [ 'class' => 'yii\gii\Module', ]; } return $config; ?>
上述結構定義了不調用堆疊來顯示錯誤,site/error 動作將被執行。
第7步 - 修改 SiteController 中的 actions() 方法。
public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], ]; }
上面的代碼定義:當錯誤發生時,錯誤(error.php)視圖將被渲染。
第8步 - 在 views/site 目錄下創建一個 error.php 檔。
<?php /* @var $this yii\web\View */ /* @var $name string */ /* @var $message string */ /* @var $exception Exception */ use yii\helpers\Html; $this->title = $name; ?> <div class = "site-error"> <h2>customized error</h2> <h1><?= Html::encode($this->title) ?></h1> <div class = "alert alert-danger"> <?= nl2br(Html::encode($message)) ?> </div> <p> The above error occurred while the Web server was processing your request. </p> <p> 這是一個自定義的錯誤顯示頁面。 </p> </div>