【问题标题】:Symfony2 array to string conversion error handling in production生产中的 Symfony2 数组到字符串转换错误处理
【发布时间】:2017-02-22 11:03:50
【问题描述】:

这里是业余爱好者。

使用 Symfony 2.6.13。

生产环境:AWS Linux、Elastic Beanstalk。 开发环境:WAMP。

我有一个让我感到困惑的错误,因为它只会导致我在开发中出现问题。以下是生产错误日志的摘录:

[Wed Feb 22 10:40:16.484644 2017] [:error] [pid 12453] [client 172.31.46.85:18619] PHP Notice:  Array to string conversion in /var/app/current/app/cache/prod/twig/db/dbafcb45562bb5839ccefc3c501bc398a96f8c34fd19c0f11d60122efe04cb15.php on line 220, referer: https://xxx-xxx.xxx.com/contact/986513/risk/1

我在生产和开发环境中都收到此错误。在生产中,错误似乎被忽略并且页面加载。在开发中,该错误不会被忽略,并且页面错误说明如下:

CRITICAL: Uncaught PHP Exception Twig_Error_Runtime: "An exception has been thrown during the rendering of a template ("Notice: Array to string conversion")

为什么在生产中会忽略此错误,但在开发中不会?

【问题讨论】:

  • 可能是因为生产没有像开发那样在php.ini中配置错误报告。在模板中找到它试图显示的变量,因为它是一个字符串。我的意思是你有没有尝试解决这个问题?
  • ive 反映了 WAMP 中的开发设置。我已经关闭了 wamp 和 AWS(生产)的错误报告。
  • 您可能在 twig 中使用了 {{variable}},变量将是数组类型,这是您遇到异常的原因之一。
  • @user1077250 在开发环境中关闭错误报告不是解决方案。此外,这个错误似乎并不难。查看模板中的变量,将每个变量放入 dump() 函数中,看看哪个是意外数组。像这样:{{ dump(someVar) }}.
  • "在开发过程中需要将错误直接转储到屏幕上(除非您有其他方法会在您的脸上抛出所有错误),在生产中您需要相同的错误报告,而不是输出可见的错误,你希望它只记录它们。” stackoverflow.com/a/17135464/2484968

标签: php symfony amazon-web-services


【解决方案1】:

我的问题的答案是我不知道开发环境和生产环境之间的区别。我期待我在开发中收到的错误也会在生产中导致相同类型的错误并停止页面加载。

我需要更详细地了解这两种环境之间的区别。

【讨论】:

    【解决方案2】:

    尝试在渲染前立即将error_reporting 设置为'0',然后再将其设置回原来的值。

    这可以防止引发“数组到字符串转换”错误,否则会完全停止渲染模板。

    相反,您会看到它在呈现的文本中输出为Array

    我们可以使用ini_set() 轻松实现这一点。

    以下示例。


    我的 twig helper 类的渲染方法看起来像这样,效果很好:

        public function render(string $name, array $params): string
        {
            $this->setIniSettings();
    
            try {
                $result = $this->twig->render($name, $params);
            } catch (\Throwable $e) {
                $this->restoreIniSettings();
                throw $e;
            }
    
            $this->restoreIniSettings();
            return $result;
        }
    

    我有一个配置文件,它定义了渲染树枝模板设置的 ini 设置,如下所示:

    return [
        'ini_settings' => [
            'error_reporting' => '0'
        ],
    ];
    

    setIniSettings() 中,我只是遍历我在配置文件中定义的一组设置,如下所示:

        protected function setIniSettings()
        {
            $this->oldIniSettings = [];
    
            foreach (config('twig.ini_settings', []) as $setting => $value) {
                $this->oldIniSettings[$setting] = ini_set($setting, $value);
            }
        }
    

    然后restoreIniSettings() 看起来像这样:

        protected function restoreIniSettings()
        {
            foreach ($this->oldIniSettings as $setting => $value) {
                ini_set($setting, $value);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 2012-07-15
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      相关资源
      最近更新 更多