Skip to main content
FAQ Component
Question
How do you handle errors in PHP, and what practices do you follow for logging in production environments?
Answer

Handling Errors in PHP

PHP provides multiple ways to handle errors effectively. The approach depends on whether you're in a development or production environment.

1️⃣ Error Handling Mechanisms in PHP

  1. Using try...catch for Exception Handling
    Wrap critical code inside a try...catch block to gracefully handle exceptions.

    try {
        $result = 10 / 0; // Division by zero
    } catch (Exception $e) {
        echo "Caught Exception: " . $e->getMessage();
    }
    
  2. Custom Error Handling with set_error_handler()
    Convert PHP errors into exceptions for better handling.

    function customErrorHandler($errno, $errstr, $errfile, $errline) {
        throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    }
    set_error_handler("customErrorHandler");
    
  3. Using register_shutdown_function() for Fatal Errors
    Detect fatal errors that would normally stop execution.

    function shutdownHandler() {
        $error = error_get_last();
        if ($error && $error['type'] === E_ERROR) {
            error_log("Fatal Error: " . $error['message']);
        }
    }
    register_shutdown_function('shutdownHandler');
    

Logging Practices in Production Environments

In production, logging errors instead of displaying them is critical for security and stability.

1️⃣ Disable Error Display in Production (php.ini)

Edit php.ini:

display_errors = Off log_errors = On error_log = /var/log/php_errors.log

2️⃣ Use error_log() for Custom Logging

error_log("Custom error message", 3, "/var/log/php_errors.log");

3️⃣ Use Monolog for Advanced Logging

Monolog provides structured logging with different log levels.

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger('app');
$log->pushHandler(new StreamHandler('/var/log/app.log', Logger::WARNING));

$log->warning('This is a warning log');
$log->error('This is an error log');

4️⃣ Logging in Drupal

Drupal provides the Watchdog logging system:

\Drupal::logger('custom_module')->error('An error occurred: @message', ['@message' => $errorMessage]);

In production, use Syslog or Redis logging for better performance.


Best Practices for Error Handling and Logging

Use try...catch blocks for expected errors.
Log errors instead of displaying them in production.
Disable error reporting in production (display_errors = Off).
Use structured logging with Monolog or Drupal's logger().
Monitor logs using tools like ELK Stack, Splunk, or Loggly.
Implement alerting mechanisms (email, Slack, or monitoring tools) for critical errors.