Yaf實現了一套錯誤和異常捕獲機制, 主要是對常見的錯誤處理和異常捕獲方法做了一個簡單抽象, 方便應用組織自己的錯誤統一處理邏輯。
前題是需要配置過或是在程序中啟用
1、配置
> application.dispatcher.throwException=1
application.dispatcher.catchException=1
2、在程序中啟用
> Yaf_Dispatcher::throwException(true)
在application.dispatcher.catchException(配置文件, 或者可通過Yaf_Dispatcher::catchException(true))開啟的情況下, 當Yaf遇到未捕獲異常的時候, 就會把運行權限, 交給當前模塊的Error Controller的Error Action動作, 而異常或作為請求的一個參數, 傳遞給Error Action.
#### 新建一個Error Controller
`<?php
class ErrorController extends Yaf_Controller_Abstract
{
public function errorAction($exception)
{
assert($exception);
$this->getView()->assign("code", $exception->getCode());
$this->getView()->assign("message", $exception->getMessage());
$this->getView()->assign("line", $exception->getLine());
}
}
?>`
#### 新建一個Error顯示模板文件
`<html>
<head>
<meta charset="utf-8">
<title>Error Page <{$code}></title>
<style>
body{background-color:#f0c040}
h2{color:#fafafa}
</style>
</head>
<body>
<h2>Error Page</h2>
<p>Error Code:<{$code}></p>
<p>Error Message:<{$message}></p>
<p>Error Line:<{$line}></p>
</body>
</html>`
### 在Bootstrap.php中新建一個error_handler方法
`public static function error_handler($errno, $errstr, $errfile, $errline)
{
if (error_reporting() === 0) return;
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}`
### 在Bootstrap.php中初始化ErrorHandler
`public function _initErrorHandler(Yaf_Dispatcher $dispatcher)
{
$dispatcher->setErrorHandler(array(get_class($this),'error_handler'));
}`
這樣當有有程序異常時會轉到ErrorController
