【问题标题】:Display all exception messages in zend instead of "An error occurred"?在zend中显示所有异常消息而不是“发生错误”?
【发布时间】:2017-10-27 07:32:13
【问题描述】:

在 Zend 2 和 Zend 3 中,我遇到了这个问题。 以下代码生成找不到“YourModule\Controller\ClassName”,因为我没有导入类 ClassName。

<?php
public function indexAction() {
    $x = new ClassName() ; //I've not imported ClassName, which raise the  error.
}

当这些类型的一些异常发生时,控件会转到 onDistpach (DispatchListner) 中的 catch 部分。如果我在这个 catch 块中回显 $ex->getMessage() 它会打印正确的错误消息 eg: "YourModule\Controller\ClassName" not found。

public function onDispatch(MvcEvent $e)
{
    ....

} catch (\Throwable $ex) {
            $caughtException = $ex; //HERE
        //$ex->getMessage() ;
}

但是zend渲染的最终输出如下。没有关于发生异常的信息。

An error occurred 执行过程中发生错误;

请稍后再试。

没有可用的例外

大多数其他情况下,它会打印正确的堆栈跟踪。如何配置 zend 以显示这些错误消息,而无需在 Zend-Mvc 中编辑 DispatchListner ?

编辑: 我尝试在异常之前打开 error_reporting() 和 display_errors。 还尝试尝试捕获生成异常但仍然无法正常工作的代码。 还有我的module.config。

'view_manager' => array(
    'display_not_found_reason' => true,
    'display_exceptions' => true,
...

【问题讨论】:

标签: php zend-framework2 zend-framework3


【解决方案1】:

可以通过将侦听器附加到 MvcEvent::EVENT_RENDER_ERROR 和 MvcEvent::EVENT_DISPATCH_ERROR 来跟踪调度和渲染中的异常。这是 ZF3 解决方案可能也适用于 ZF2。

带有红色标题的我自己的错误渲染函数。

public function exception($e) {
    echo "<span style='font-family: courier new; padding: 2px 5px; background:red; color: white;'> " . $e->getMessage() . '</span><br/>' ;
    echo "<pre>" . $e->getTraceAsString() . '</pre>' ;   
}

在引导程序上附加监听器

public function onBootstrap(MvcEvent $e)
{
    $eventManager        = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);

    //Attach render errors
    $eventManager->attach(MvcEvent::EVENT_RENDER_ERROR, function($e)  {
        if ($e->getParam('exception')) {
            $this->exception( $e->getParam('exception') ) ; //Custom error render function.
        }
    } );
    //Attach dispatch errors
    $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function($e)  {
        if ($e->getParam('exception')) {
            $this->exception( $e->getParam('exception') ) ;//Custom error render function.
        }
    } );
}

【讨论】:

  • 您的解决方案有效。我只是不明白为什么 ZF 消除了这些错误
【解决方案2】:

在您的module.config.php 文件中将display_exceptions 设置为true:

<?php
 'view_manager' => array(    
 'display_not_found_reason' => true,
 'display_exceptions'       => true, // SET TO true

在生产环境中工作时不要忘记将其设置回 false。

【讨论】:

  • 我在 module.config.php (ZF3) 中将这些设置设置为 true,但仍然没有看到异常。
猜你喜欢
  • 2012-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
相关资源
最近更新 更多