【问题标题】:symfony 1.4: How to pass exception message to error.html.php?symfony 1.4:如何将异常消息传递给error.html.php?
【发布时间】:2011-08-16 09:22:58
【问题描述】:

我尝试使用此处描述的特殊变量 $message http://www.symfony-project.org/cookbook/1_2/en/error_templates 但似乎该变量未在 symfony 1.4 中定义,至少它不包含以这种方式传递给异常的消息 throw new sfException('some message')

您知道将此消息传递给 error.html.php 的其他方法吗?

【问题讨论】:

    标签: exception symfony1 symfony-1.4


    【解决方案1】:

    您需要进行一些自定义错误处理。我们自己实现了一个自定义 symfony 动作的转发。不过要小心,此操作本身也可能触发异常,您需要考虑到这一点。

    以下内容可能是一个好的开始。首先为事件添加一个监听器,一个好地方是 ProjectConfiguration.class.php:

    $this->dispatcher->connect('application.throw_exception', array('MyClass', 'handleException'));
    

    使用事件处理程序可能足以满足您想要对异常执行的操作,例如,如果您只想将堆栈跟踪发送给管理员。我们希望转发到自定义操作以显示和处理反馈表。我们的事件处理程序看起来像这样:

    class MyClass {
      public static function handleException(sfEvent $event) {
        $moduleName = sfConfig::get('sf_error_500_module', 'error');
        $actionName = sfConfig::get('sf_error_500_action', 'error500');
        sfContext::getInstance()->getRequest()->addRequestParameters(array('exception' => $event->getSubject()));
        $event->setReturnValue(true);
        sfContext::getInstance()->getController()->forward($moduleName, $actionName);
      }
    }
    

    您现在可以在 settings.yml 中配置要转发到异常的模块和操作

    all:
      .actions:
        error_500_module:       error
        error_500_action:       error500
    

    在动作本身中,您现在可以做任何您想做的事情,除了例外,例如。显示反馈表以联系管理员。您可以使用 $request->getParameter('exception')

    获取异常本身

    【讨论】:

    • +1 非常感谢!我们的系统支持主题化,如果没有这个,我们也无法支持错误 500 页面的主题化。非常感谢。
    • 感谢您的回答!是否将您的自定义函数连接到 application.throw_exception overwrite symfony 在该事件上的默认行为?如果是,我可以通过在自定义函数中调用self::parent() 来阻止它吗?我只是想添加一些功能..
    • @Tapper 你应该可以通过修改返回值来实现,尝试 $event->setReturnValue(false) 代替
    【解决方案2】:

    我想我找到了一个更简单的答案。在 Symfony 1.4 上,$message 确实没有定义,但 $exception 是(它包含异常对象)。

    所以只需回显$exception->message

    等等!

    【讨论】:

      【解决方案3】:

      我发现了另一个技巧——sfContext 可用于将异常消息传递给error.html.php,但必须使用自定义函数来引发异常。例如:

      class myToolkit {
        public static function throwException($message) 
          {
            sfContext::getInstance()->set('error_msg', $message);
            throw new sfException($message);
          }
      

      你应该使用throw new sfException('some message')而不是使用myToolkit::throwException('some message')

      要在error.html.php 中显示消息,请使用<?php echo sfContext::getInstance()->get('error_msg') ?>

      【讨论】:

        猜你喜欢
        • 2016-02-19
        • 1970-01-01
        • 1970-01-01
        • 2021-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-07
        • 1970-01-01
        相关资源
        最近更新 更多