Yii錯誤處理


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");
}
第5步 - 存取以下URL => http://localhost:8080/index.php?r=site/show-error 會看到下面的HTTP錯誤。

當 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>
第9步 - 開啟 http://localhost:8080/index.php?r=site/show-error ,將看到自定義的錯誤檢視。
Yii錯誤處理