我正在尝试为 404、403、5xx 错误制作自定义错误页面。我按照文档创建了一个错误控制器,覆盖Kohana_Exception
类并添加了一条路线。
Kohana_Exception 类
class Kohana_Exception extends Kohana_Kohana_Exception {
public static function handler(Exception $e) {
if (Kohana::DEVELOPMENT === Kohana::$environment) {
parent::handler($e);
} else {
try {
Kohana::$log->add(Log::ERROR, parent::text($e));
$attributes = array('action' => 500, 'message' => rawurlencode($e->getMessage()));
if ($e instanceof HTTP_Exception) {
$attributes['action'] = $e->getCode();
}
// Error sub-request.
echo Request::factory(Route::get('error')->uri($attributes))->execute()->send_headers()->body();
}
catch(Exception $e) {
// Clean the output buffer if one exists
ob_get_level() and ob_clean();
// Display the exception text
echo parent::text($e);
// Exit with an error status
exit(1);
}
}
}
}
错误控制器
<?php defined('SYSPATH') OR die('No direct access allowed.');
class Controller_Error extends Webim_Template {
public function before() {
parent::before();
$this->template->page = URL::site(rawurldecode(Request::$initial->uri()));
// Internal request only!
if (Request::$initial !== Request::$current) {
if ($message = rawurldecode($this->request->param('message'))) {
$this->template->message = $message;
}
} else {
$this->request->action(404);
}
$this->response->status((int)$this->request->action());
}
public function action_404() {
$this->template->title = __('404 Not Found');
// Here we check to see if a 404 came from our website. This allows the
// webmaster to find broken links and update them in a shorter amount of time.
if (isset($_SERVER['HTTP_REFERER']) AND strstr($_SERVER['HTTP_REFERER'], $_SERVER['SERVER_NAME']) !== FALSE) {
// Set a local flag so we can display different messages in our template.
$this->template->local = TRUE;
}
// HTTP Status code.
$this->response->status(404);
}
public function action_403() {
$this->request->redirect('welcome');
}
public function action_503() {
$this->template->title = __('Maintenance Mode');
}
public function action_500() {
$this->template->title = __('Internal Server Error');
}
}
路线
Route::set('error', 'error/<action>(/<message>)',
array('action' => '[0-9]++', 'message' => '.+'))
->defaults(array(
'controller' => 'error_handler'
));
Route::set('default', '(<controller>(/<action>(/<id>)))')
->defaults(array(
'controller' => 'welcome',
'action' => 'index',
));
当我抛出HTTP_Exception_403
异常时,它不会welcome
根据错误控制器重定向到应有的位置。我想我在这里错过了非常简单的事情。
我对其进行了调试,发现执行点没有到达我的控制器。所以这可能是Route中的一个问题。什么是正确的路线?真正的问题是什么?