You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Symfony 3.4生产环境下将所有错误转为异常并终止应用?

How to Treat All PHP Errors as Exceptions in Symfony 3.4 (Without Enabling Debug Mode)

I get it—you want your Symfony 3.4 app to treat every PHP error (notices, warnings, etc.) as an exception that terminates execution, just like JavaScript's "use strict" mode, but without relying on debug mode (which isn't safe for production). Here's how to do it:

Step 1: Enable Full Error Reporting

First, make sure PHP is configured to report all errors. In your production front controller (web/app.php), update the error reporting settings to catch everything:

// web/app.php
error_reporting(E_ALL);
ini_set('display_errors', 0); // Keep errors hidden from end users

By default, Symfony's production environment suppresses some non-critical errors, but we need to ensure every error is flagged.

Step 2: Convert PHP Errors to Exceptions

PHP doesn't natively throw exceptions for notices or warnings—we need to add a custom error handler to convert these errors into ErrorException instances. This will make Symfony treat them like any other uncaught exception, which will terminate the app and trigger your production error handling flow.

Add this code in web/app.php before initializing the Symfony kernel:

// Convert all PHP errors to exceptions
set_error_handler(function ($severity, $message, $file, $line) {
    // Skip errors that aren't in our error_reporting scope
    if (!(error_reporting() & $severity)) {
        return false;
    }
    // Throw an ErrorException for the error
    throw new \ErrorException($message, 0, $severity, $file, $line);
});

Step 3: Verify Symfony's Exception Handling Takes Over

Once errors are converted to exceptions, Symfony's production exception handler will automatically catch them, log the details (check var/logs/prod.log), and display your custom 500 error page to users. Uncaught exceptions will terminate the app immediately, just like you want.

Important Notes

  • Parse Errors: This handler won't catch parse errors (like syntax mistakes) because those are detected before your code runs. You'll still need to fix those during development.
  • Testing: Enable this in a staging environment first—you might uncover hidden notices or warnings that were previously ignored but could cause issues in production.
  • Performance: While this adds a tiny overhead, it's negligible for most production apps and worth it for stricter error handling.

内容的提问来源于stack exchange,提问作者jgmjgm

火山引擎 最新活动