Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Exception Handling in Kohana3

I have a requirement to create custom exception for the exceptions generated by my app/module.

  • I want to consolidate all the exception classes in one place and handle the exceptions in one place.
  • I might have generic exceptions, like mentioned below, which I would like in one common place
    • input invalid
    • internal error (database errors, smtp errors, other failures)
    • permission denied
    • session error
  • I might have specific exceptions, like mentioned below

    • email not valid, etc.
  • Specific exceptions might be a subclass of generic exceptions in cases, like "email not valid" could fall under "input invalid" exception.

  • I Should be able to send data along with the exception message while throwing. (Data will be in arrays or objects if feasible)

Whats the best way to go about it?
What is the best way to organize custom exceptions?
How to code in such a way that we don't have to catch common exceptions every where but at the same time user gets a meaningful error.
After calling a method we should only catch specific exceptions that the method can throw.

like image 263
Shrinath Avatar asked Dec 21 '22 11:12

Shrinath


1 Answers

I would suggest you to move to Kohana 3.2 as there is a change in the way Kohana handles exception in that new stable version. Assuming you are going to use v3.2, this is how you could manage custom exceptions:

First of all, you need to modify bootstrap.php and make sure 'errors' is to true in the Kohana::init() call. This will make sure that Koahana will handle all unhandled exceptions thrown by you or the system. if you check \classes\kohana\core.php, Kohana registers its exception handler class Kohana_Exception using php call below

set_exception_handler(array('Kohana_Exception', 'handler'));

The default exception handler does a nice job of handling all types of Exceptions and writing the message to the log folder and displaying a basic error page. If you look inside Kohana_Exception, it is a subclass of Kohana_Kohana_Exception class, which is where the logic is written.

Now, to customize things:

  • If you are looking for just showing a custom page for showing your errors, just create a view named application/views/kohana/error.php and put your custom error page there. it will override the system's default error view file found at system/views/kohana/error.php.

  • If you are looking for changing the way you log the error or do some custom processing based on specific type of errors, you need to override Kohana_Exception class or register your own derived exception handler by calling set_exception_handler() at the end of bootstrap.php.

    • To override Kohana_Exception, just copy paste /system/classes/kohana/exception.php to application/classes/kohana/exception.php and override the handler() and/or text() method. for e.g. below I am custom handling 404 error and also including user_id to error log for debugging.

:

class Kohana_Exception extends Kohana_Kohana_Exception 
{
    /**
     * Overriden to show custom page for 404 errors
     */
    public static function handler(Exception $e)
    {
        switch (get_class($e))
        {
            case 'HTTP_Exception_404':
                $response = new Response;
                $response->status(404);
                $view = new View('error/report_404');
                $view->message = $e->getMessage();
                echo $response->body($view)->send_headers()->body();
                if (is_object(Kohana::$log))
                {
                    // Add this exception to the log
                    Kohana::$log->add(Log::ERROR, $e);
                    // Make sure the logs are written
                    Kohana::$log->write();
                }                
                return TRUE;
                break;

            default:
                return Kohana_Kohana_Exception::handler($e);
                break;
        }
    }

  /**
    * Override if necessary.  E.g. below include logged in user's info in the log
   */
   public static function text(Exception $e)
   {

    $id = <get user id from session>;
    return sprintf('[user: %s] %s [ %s ]: %s ~ %s [ %d ]',
            $id, get_class($e), $e->getCode(), strip_tags($e->getMessage()), Debug::path($e->getFile()), $e->getLine());        

   }
}

Helpful external links and references:

http://kohana.sebicas.com/index.php/guide/kohana/errors

http://kohanaframework.org/3.1/guide/kohana/tutorials/error-pages

like image 200
Murukesh Avatar answered Mar 24 '23 03:03

Murukesh