2012-05-08 48 views
1

我正在爲Kohana編寫錯誤處理程序。有一個控制器Controller_Errors(它繼承Controller_Kohana_Errors)與action_500action_404動作,action_403,等檢查Kohana中是否存在動作

路線:

Route::set('errors','errors/<action>', array (
     'action' => '[\d]{3}', 
    )) 
    ->defaults(array(
     'controller' => 'errors', 
    )); 

包含的樣本bootstrap.php中

try { 
    $response = Request::factory()->execute(); 
} catch (Exception $e) { 
    // If we are in development and the error wasn't a 404, show the stack trace. 
    // Otherwise, show a nice error. 
    if ((Kohana::$environment == KOHANA::DEVELOPMENT) AND (! ($e->getCode() == 404 OR $e->getCode() == 403))) { 
     throw $e; 
    } 
    // Log the error 
    Kohana::$log->add(Log::ERROR, Kohana_Exception::text($e)); 

    $error_code = 500; 
    if ($e instanceof ReflectionException) { 
     $error_code = 404; 
    } 
    if ($e instanceof HTTP_Exception) 
    { 
     $error_code = $e->getCode(); 
    } 
    $request = Request::factory('errors/'.$error_code); 
    if (*__NOT SURE WHAT GOES HERE__*) { 
     $request = Request::factory('errors/500'); 
    } 
    $response = $request->execute(); 
} 

// Send the headers and echo the response 
echo $response->send_headers()->body(); 

我想讓人們擴展我的課程,所以我需要一些方法來解決問題如果存在動作,如果不存在,則更改爲顯示500錯誤。 (見上面寫着*__NOT SURE WHAT GOES HERE__*行了。)

回答

1

我認爲下面的代碼將做到這一點:

if ($request->status == 404 && $error_code != 404) ... 

在這種情況下,你知道404並非來自原始請求,因此必須來自attmpt加載錯誤代碼的錯誤頁面。

+0

這將需要它在另一個try/catch執行請求。這看起來並不是最有效的方式。 – yakatz

+0

爲什麼它必須在另一個try/catch內?哪部分是拋出另一個異常? –

+0

'$ request = Request :: factory('errors /'.$ error_code);'不設置狀態。你需要首先調用execute(),然後拋出一個異常。 – yakatz