Как настроить пользовательскую страницу 404 для приложения Kohana v3 - PullRequest
5 голосов
/ 16 декабря 2010

Как это можно сделать? Я пытаюсь сделать это около получаса, и это становится довольно раздражающим. Вы должны это, это должно быть простой и простой в настройке для такой платформы. Я надеюсь, что, возможно, есть простой способ, который я пропустил, потому что я начинаю понимать, что мне вообще не следует выбирать этот фреймворк, если такие базовые настройки так сложно настроить.

Это мой файл bootstrap.php, который должен помочь.

if ( ! defined('SUPPRESS_REQUEST'))
{
    /**
     * Execute the main request. A source of the URI can be passed, eg: $_SERVER['PATH_INFO'].
     * If no source is specified, the URI will be automatically detected.
     */ 
    $request = Request::instance();
    try
    {
        // Attempt to execute the response
        $request->execute();
    }
    catch (Exception $e)
    {
        if (Kohana::$environment === Kohana::DEVELOPMENT)
        {
            // Just re-throw the exception
            throw $e;
        }
        echo "ok";
        // Create a 404 response
        $request->status = 404;
        $view = View::factory('error404');
        $request->response = $view->render();
    }

    echo $request->send_headers()->response;
}

Но я все еще получаю

Fatal error: Uncaught Kohana_Request_Exception [ 0 ]: Unable to find a route to match the URI: test ~ SYSPATH\classes\kohana\request.php [ 674 ] thrown in C:\Xampp\htdocs\system\classes\kohana\request.php on line 674

вместо моей пользовательской страницы 404. И да, Kohana::$environment установлен на Kohana::PRODUCTION;

Это даже не доходит до echo "ok"; части. Почему исключение не ловится?

Ответы [ 3 ]

7 голосов
/ 19 декабря 2010

Заменить последнюю строку bootstrap.php на:

/**
* Set the production status
*/
define('IN_PRODUCTION', FALSE);

/**
* Execute the main request. A source of the URI can be passed, eg: $_SERVER['PATH_INFO'].
* If no source is specified, the URI will be automatically detected.
*/
$request = Request::instance();

try
{
    $request->execute();
}
catch (Kohana_Exception404 $e)
{
    $request = Request::factory('error/404')->execute();
}
catch (Kohana_Exception403 $e)
{
    $request = Request::factory('error/403')->execute();
}
catch (ReflectionException $e)
{
    $request = Request::factory('error/404')->execute();
}
catch (Kohana_Request_Exception $e)
{
    $request = Request::factory('error/404')->execute();
}
catch (Exception $e)
{
    if ( ! IN_PRODUCTION )
    {
        throw $e;
    }

    $request = Request::factory('error/500')->execute();
}

echo $request->send_headers()->response;

Создать новый контроллер " error.php ":

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Error extends Controller {

    public function action_404()
    {
        $this->request->status = 404;
        $this->request->headers['HTTP/1.1'] = '404';
        $this->request->response = 'error 404';
    }

    public function action_403()
    {
        $this->request->status = 403;
        $this->request->headers['HTTP/1.1'] = '403';
        $this->request->response = 'error 403';
    }

    public function action_500()
    {
        $this->request->status = 500;
        $this->request->headers['HTTP/1.1'] = '500';
        $this->request->response = 'error 500';
    }
} // End Error

Создание двух файлов ( исключение 404.php и исключение 403.php ) в папке " кохана ":

<?php defined('SYSPATH') or die('No direct access');

class Kohana_Exception403 extends Kohana_Exception {

    public function __construct($message = 'error 403', array $variables = NULL, $code = 0)
    {
        parent::__construct($message, $variables, $code);
    }

} // End Kohana_Exception 403


<?php defined('SYSPATH') or die('No direct access');

class Kohana_Exception404 extends Kohana_Exception {

    public function __construct($message = 'error 404', array $variables = NULL, $code = 0)
    {
        parent::__construct($message, $variables, $code);
    }

} // End Kohana_Exception 404

Теперь вы можетевыдает 404 и 403 ошибки вручную (ошибка 500 не выдается;)

throw new Kohana_Exception404;
throw new Kohana_Exception403;
6 голосов
/ 02 февраля 2012

Все, что вам нужно сделать, это установить путь к другому представлению в вашем bootstrap.php add:

Kohana_Exception::$error_view = 'error/myErrorPage';

, который будет анализировать все переменные, которые в настоящее время анализируются на странице ошибки, которая находится в:

system/views/kohana/error.php

т.е.:

<h1>Oops [ <?= $code ?> ]</h1>
<span class="message"><?= html::chars($message) ?></span>
5 голосов
/ 12 мая 2011

Начиная с версии 3.1, руководство по Kohana включает в себя учебник по пользовательским страницам ошибок , который показывает гораздо более чистый способ решения этого вопроса.

...