Kohana v3 :: Custom 404 Page

A best practice for a web app/site in “production” is have an error page that looks like its part of your website – kind of a friendly error page. With Kohana v3 this is fairly easy to do, and only requires one new file, and a modification to one other file.

Note: This solution was found in the Kohana Forums.

Step 1 : application/boostrap.php

Define ‘IN_PRODUCTION’ in the Environment Setup Section


define('IN_PRODUCTION', true);

Catch the Exception coming from any invalid Request

After you define all your Routes, Kohana executes the request, sends the headers and renders the view. If you haven’t already made changes, it looks like this:


echo Request::instance()
->execute()
->send_headers()
->response;

Here is the replacement you should make, with comments to explain:

// Instantiate your Request object
$request = Request::instance();
// The give it a try, to see if its a valid request
try
{
$request->execute();
}
catch (Exception $e) // if its not valid, it gets caught here
{
if (! IN_PRODUCTION) // if this is Development, its displays the error
{
throw $e;
}
// if its IN_PRODUCTION, it does the following:
// Logs the error
Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e));
// Marks the status as 404
$request->status = 404;
// Renders the View for your CUSTOM 404 of your choice
$request->response = View::factory('public/templates/main') //your view may be different
->set('title', '404')
->set('content', View::factory('errors/404')); //again, your view may be different
}
// then continues on with the request process to display your custom 404 page
$request->send_headers()->response;
echo $request->response;

Step 2 : Create A Custom Error View

Create a new folder in your views folder called “Kohana”

Create a file in that folder called “error.php”

Whatever you put in your application/views/Kohana/error.php file will take precedents over Kohana’s views/Kohana/error.php file, so this is where I styled my error page to look like the rest of my public application. I copied much of the error reporting code directly from Kohana’s error file and used a conditional to display it in development or display a friendlier message in production. See the code skeleton:


if (IN_PRODUCTION) ///defined in boostrap.php
/* Render your friendly error message */
else
/* Render Kohana's error which you copied from views/Kohana/error.php */

Leave a Reply