# 錯誤處理
Yii 內置了一個yii\web\ErrorHandler錯誤處理器,它使錯誤處理更方便, Yii錯誤處理器做以下工作來提升錯誤處理效果:
* 所有非致命PHP錯誤(如,警告,提示)會轉換成可獲取異常;
* 異常和致命的PHP錯誤會被顯示,在調試模式會顯示詳細的函數調用棧和源代碼行數。
* 支持使用專用的?[控制器操作](http://www.yiichina.com/doc/guide/2.0/structure-controllers#actions)?來顯示錯誤;
* 支持不同的錯誤響應格式;
yii\web\ErrorHandler 錯誤處理器默認啟用, 可通過在應用的[入口腳本](http://www.yiichina.com/doc/guide/2.0/structure-entry-scripts)中定義常量`YII_ENABLE_ERROR_HANDLER`來禁用。
## 使用錯誤處理器
yii\web\ErrorHandler 注冊成一個名稱為`errorHandler`[應用組件](http://www.yiichina.com/doc/guide/2.0/structure-application-components), 可以在應用配置中配置它類似如下:
~~~
return [
'components' => [
'errorHandler' => [
'maxSourceLines' => 20,
],
],
];
~~~
使用如上代碼,異常頁面最多顯示20條源代碼。
如前所述,錯誤處理器將所有非致命PHP錯誤轉換成可獲取異常,也就是說可以使用如下代碼處理PHP錯誤:
~~~
use Yii;
use yii\base\ErrorException;
try {
10/0;
} catch (ErrorException $e) {
Yii::warning("Division by zero.");
}
// execution continues...
~~~
如果你想顯示一個錯誤頁面告訴用戶請求是無效的或無法處理的,可簡單地拋出一個 yii\web\HttpException異常, 如 yii\web\NotFoundHttpException。錯誤處理器會正確地設置響應的HTTP狀態碼并使用合適的錯誤視圖頁面來顯示錯誤信息。
~~~
use yii\web\NotFoundHttpException;
throw new NotFoundHttpException();
~~~
## 自定義錯誤顯示
yii\web\ErrorHandler錯誤處理器根據常量`YII_DEBUG`的值來調整錯誤顯示, 當`YII_DEBUG`?為 true (表示在調試模式),錯誤處理器會顯示異常以及詳細的函數調用棧和源代碼行數來幫助調試, 當`YII_DEBUG`?為 false,只有錯誤信息會被顯示以防止應用的敏感信息泄漏。
> 補充: 如果異常是繼承 yii\base\UserException,不管`YII_DEBUG`為何值,函數調用棧信息都不會顯示, 這是因為這種錯誤會被認為是用戶產生的錯誤,開發人員不需要去修正。
yii\web\ErrorHandler 錯誤處理器默認使用兩個[視圖](http://www.yiichina.com/doc/guide/2.0/structure-views)顯示錯誤:
* `@yii/views/errorHandler/error.php`: 顯示不包含函數調用棧信息的錯誤信息是使用, 當`YII_DEBUG`?為 false時,所有錯誤都使用該視圖。
* `@yii/views/errorHandler/exception.php`: 顯示包含函數調用棧信息的錯誤信息時使用。
可以配置錯誤處理器的 yii\web\ErrorHandler::errorView 和 yii\web\ErrorHandler::exceptionView 屬性 使用自定義的錯誤顯示視圖。
### 使用錯誤操作
使用指定的錯誤[操作](http://www.yiichina.com/doc/guide/2.0/structure-controllers)?來自定義錯誤顯示更方便, 為此,首先配置`errorHandler`組件的 yii\web\ErrorHandler::errorAction 屬性,類似如下:
~~~
return [
'components' => [
'errorHandler' => [
'errorAction' => 'site/error',
],
]
];
~~~
yii\web\ErrorHandler::errorAction 屬性使用[路由](http://www.yiichina.com/doc/guide/2.0/structure-controllers#routes)到一個操作, 上述配置表示不用顯示函數調用棧信息的錯誤會通過執行`site/error`操作來顯示。
可以創建`site/error`?操作如下所示:
~~~
namespace app\controllers;
use Yii;
use yii\web\Controller;
class SiteController extends Controller
{
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
}
~~~
上述代碼定義`error`?操作使用yii\web\ErrorAction 類,該類渲染名為`error`視圖來顯示錯誤。
除了使用yii\web\ErrorAction, 可定義`error`?操作使用類似如下的操作方法:
~~~
public function actionError()
{
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
return $this->render('error', ['exception' => $exception]);
}
}
~~~
現在應創建一個視圖文件為`views/site/error.php`,在該視圖文件中,如果錯誤操作定義為yii\web\ErrorAction, 可以訪問該操作中定義的如下變量:
* `name`: 錯誤名稱
* `message`: 錯誤信息
* `exception`: 更多詳細信息的異常對象,如HTTP 狀態碼,錯誤碼,錯誤調用棧等。
> 補充: 如果你使用?[基礎應用模板](http://www.yiichina.com/doc/guide/2.0/start-installation)?或?[高級應用模板](http://www.yiichina.com/doc/guide/2.0/tutorial-advanced-app), 錯誤操作和錯誤視圖已經定義好了。
### 自定義錯誤格式
錯誤處理器根據[響應](http://www.yiichina.com/doc/guide/2.0/runtime-responses)設置的格式來顯示錯誤, 如果yii\web\Response::format 響應格式為`html`, 會使用錯誤或異常視圖來顯示錯誤信息,如上一小節所述。 對于其他的響應格式,錯誤處理器會錯誤信息作為數組賦值給yii\web\Response::data屬性,然后轉換到對應的格式, 例如,如果響應格式為`json`,可以看到如下響應信息:
~~~
HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
{
"name": "Not Found Exception",
"message": "The requested resource was not found.",
"code": 0,
"status": 404
}
~~~
可在應用配置中響應`response`組件的`beforeSend`事件來自定義錯誤響應格式。
~~~
return [
// ...
'components' => [
'response' => [
'class' => 'yii\web\Response',
'on beforeSend' => function ($event) {
$response = $event->sender;
if ($response->data !== null) {
$response->data = [
'success' => $response->isSuccessful,
'data' => $response->data,
];
$response->statusCode = 200;
}
},
],
],
];
~~~
上述代碼會重新格式化錯誤響應,類似如下:
~~~
HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
{
"success": false,
"data": {
"name": "Not Found Exception",
"message": "The requested resource was not found.",
"code": 0,
"status": 404
}
}
~~~
- 介紹(Introduction)
- 關于 Yii(About Yii)
- 從 Yii 1.1 升級(Upgrading from Version 1.1)
- 入門(Getting Started)
- 安裝 Yii(Installing Yii)
- 運行應用(Running Applications)
- 第一次問候(Saying Hello)
- 使用 Forms(Working with Forms)
- 玩轉 Databases(Working with Databases)
- 用 Gii 生成代碼(Generating Code with Gii)
- 更上一層樓(Looking Ahead)
- 應用結構(Application Structure)
- 結構概述(Overview)
- 入口腳本(Entry Scripts)
- 應用(Applications)
- 應用組件(Application Components)
- 控制器(Controllers)
- 模型(Models)
- 視圖(Views)
- 模塊(Modules)
- 過濾器(Filters)
- 小部件(Widgets)
- 前端資源(Assets)
- 擴展(Extensions)
- 請求處理(Handling Requests)
- 運行概述(Overview)
- 引導(Bootstrapping)
- 路由引導與創建 URL(Routing and URL Creation)
- 請求(Requests)
- 響應(Responses)
- Sessions and Cookies
- 錯誤處理(Handling Errors)
- 日志(Logging)
- 關鍵概念(Key Concepts)
- 組件(Components)
- 屬性(Properties)
- 事件(Events)
- 行為(Behaviors)
- 配置(Configurations)
- 別名(Aliases)
- 類自動加載(Class Autoloading)
- 服務定位器(Service Locator)
- 依賴注入容器(Dependency Injection Container)
- 配合數據庫工作(Working with Databases)
- 數據庫訪問(Data Access Objects): 數據庫連接、基本查詢、事務和模式操作
- 查詢生成器(Query Builder): 使用簡單抽象層查詢數據庫
- 活動記錄(Active Record): 活動記錄對象關系映射(ORM),檢索和操作記錄、定義關聯關系
- 數據庫遷移(Migrations): 在團體開發中對你的數據庫使用版本控制
- Sphinx
- Redis
- MongoDB
- ElasticSearch
- 接收用戶數據(Getting Data from Users)
- 創建表單(Creating Forms)
- 輸入驗證(Validating Input)
- 文件上傳(Uploading Files)
- 收集列表輸入(Collecting Tabular Input)
- 多模型同時輸入(Getting Data for Multiple Models)
- 顯示數據(Displaying Data)
- 格式化輸出數據(Data Formatting)
- 分頁(Pagination)
- 排序(Sorting)
- 數據提供器(Data Providers)
- 數據小部件(Data Widgets)
- 操作客戶端腳本(Working with Client Scripts)
- 主題(Theming)
- 安全(Security)
- 認證(Authentication)
- 授權(Authorization)
- 處理密碼(Working with Passwords)
- 客戶端認證(Auth Clients)
- 安全領域的最佳實踐(Best Practices)
- 緩存(Caching)
- 概述(Overview)
- 數據緩存(Data Caching)
- 片段緩存(Fragment Caching)
- 分頁緩存(Page Caching)
- HTTP 緩存(HTTP Caching)
- RESTful Web 服務
- 快速入門(Quick Start)
- 資源(Resources)
- 控制器(Controllers)
- 路由(Routing)
- 格式化響應(Response Formatting)
- 授權驗證(Authentication)
- 速率限制(Rate Limiting)
- 版本化(Versioning)
- 錯誤處理(Error Handling)
- 開發工具(Development Tools)
- 調試工具欄和調試器(Debug Toolbar and Debugger)
- 使用 Gii 生成代碼(Generating Code using Gii)
- TBD 生成 API 文檔(Generating API Documentation)
- 測試(Testing)
- 概述(Overview)
- 搭建測試環境(Testing environment setup)
- 單元測試(Unit Tests)
- 功能測試(Functional Tests)
- 驗收測試(Acceptance Tests)
- 測試夾具(Fixtures)
- 高級專題(Special Topics)
- 高級應用模版(Advanced Project Template)
- 從頭構建自定義模版(Building Application from Scratch)
- 控制臺命令(Console Commands)
- 核心驗證器(Core Validators)
- 國際化(Internationalization)
- 收發郵件(Mailing)
- 性能優化(Performance Tuning)
- 共享主機環境(Shared Hosting Environment)
- 模板引擎(Template Engines)
- 集成第三方代碼(Working with Third-Party Code)
- 小部件(Widgets)
- Bootstrap 小部件(Bootstrap Widgets)
- jQuery UI 小部件(jQuery UI Widgets)
- 助手類(Helpers)
- 助手一覽(Overview)
- Array 助手(ArrayHelper)
- Html 助手(Html)
- Url 助手(Url)