symfony 1.4: How to pass exception message to error.html.php?

前端 未结 3 1834
情歌与酒
情歌与酒 2020-12-30 16:13

I tried using special variable $message described here http://www.symfony-project.org/cookbook/1_2/en/error_templates but it seems this variable isn\'t defined

相关标签:
3条回答
  • 2020-12-30 16:41

    I think I found a much simpler answer. On Symfony 1.4 $message is indeed not defined, but $exception is (it contains the exception object).

    So just echo $exception->message.

    Et voilà!

    0 讨论(0)
  • 2020-12-30 16:42

    You'll need to do some custom error handling. We implemented a forward to a custom symfony action ourselves. Be cautious though, this action itself could be triggering an exception too, you need to take that into account.

    The following might be a good start. First add a listener for the event, a good place would be ProjectConfiguration.class.php:

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

    Using the event handler might suffice for what you want to do with the exception, for example if you just want to mail a stack trace to the admin. We wanted to forward to a custom action to display and process a feedback form. Our event handler looked something like this:

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

    You can now configure the module and action to forward to on an exception in settings.yml

    all:
      .actions:
        error_500_module:       error
        error_500_action:       error500
    

    In the action itself you can now do whatever you want with the exception, eg. display the feedback form to contact the administrator. You can get the exception itself by using $request->getParameter('exception')

    0 讨论(0)
  • 2020-12-30 16:47

    I've found another trick to do that - sfContext can be used to pass exception message to error.html.php but custom function have to be used to throw exception. For example:

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

    than insted of using throw new sfException('some message') you should use myToolkit::throwException('some message')

    To display message in error.html.php use <?php echo sfContext::getInstance()->get('error_msg') ?>

    0 讨论(0)
提交回复
热议问题