Kohana3 中的自定义异常处理

发布于 2024-11-26 13:17:36 字数 521 浏览 0 评论 0原文

我需要为我的应用程序/模块生成的异常创建自定义异常。

  • 我想将所有异常类合并到一处,并在一处处理异常。
  • 我可能有通用的例外情况,如下所述,我希望将其放在一个共同的地方
    • 输入无效
    • 内部错误(数据库错误、smtp 错误、其他故障)
    • 权限被拒绝
    • 会话错误
  • 我可能有特定的异常,如下所述

    • 电子邮件无效等。
  • 特定异常可能是通用异常的子类,例如“电子邮件无效”可能属于“输入无效”异常。< /p>

  • 我应该能够在抛出异常时发送数据和异常消息。 (如果可行,数据将位于数组或对象中)

最好的方法是什么?
组织自定义异常的最佳方式是什么?
如何以这样的方式进行编码:我们不必在每个地方捕获常见异常,但同时用户会收到有意义的错误。
调用方法后,我们应该只捕获该方法可能抛出的特定异常。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

反话 2024-12-03 13:17:36

我建议您迁移到 Kohana 3.2,因为新的稳定版本中 Kohana 处理异常的方式发生了变化。假设您要使用 v3.2,这就是您管理自定义异常的方式:

首先,您需要修改 bootstrap.php 并确保 Kohana::init() 调用中的“errors”为 true。这将确保 Koahana 能够处理您或系统抛出的所有未处理的异常。如果您检查 \classes\kohana\core.php,Kohana 使用下面的 php 调用注册其异常处理程序类 Kohana_Exception

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

默认异常处理程序可以很好地处理所有类型的异常并将消息写入日志文件夹并显示基本错误页。如果你查看 Kohana_Exception 内部,它是 Kohana_Kohana_Exception 类的子类,逻辑是在 Kohana_Kohana_Exception 类中编写的。

现在,要自定义内容:

  • 如果您只是想显示一个自定义页面来显示您的错误,只需创建一个名为 application/views/kohana/error.php 的视图并将您的自定义错误页面放在那里。它将覆盖位于 system/views/kohana/error.php 的系统默认错误视图文件。

  • 如果您正在寻求更改记录错误的方式或根据特定类型的错误进行一些自定义处理,则需要重写 Kohana_Exception 类或通过在引导程序末尾调用 set_exception_handler() 来注册您自己的派生异常处理程序.php。

    • 要覆盖 Kohana_Exception,只需将 /system/classes/kohana/exception.php 复制粘贴到 application/classes/kohana/exception.php 并覆盖 handler() 和/或 text() 方法。例如,下面我自定义处理 404 错误,并将 user_id 包含到错误日志中以进行调试。

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());        

   }
}

有用的外部链接和参考:

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文