PHP Error Handling

PHP Error Handling

PHP offers several layers of error handling — from global error reporting settings to exceptions and custom handlers.

1 - Error Reporting

// Development — show everything
error_reporting(E_ALL);
ini_set("display_errors", "1");

// Production — log, never display
error_reporting(E_ALL);
ini_set("display_errors", "0");
ini_set("log_errors", "1");
ini_set("error_log", "/var/log/php_errors.log");

2 - try / catch / finally

try {
    $pdo = new PDO("mysql:host=localhost;dbname=app", "root", "");
    // risky operations...
} catch (PDOException $e) {
    echo "DB Error: " . $e->getMessage();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} finally {
    echo "Cleanup always runs.";
}

3 - Throwing Exceptions

function divide(int $a, int $b): float {
    if ($b === 0) {
        throw new InvalidArgumentException("Cannot divide by zero");
    }
    return $a / $b;
}

echo divide(10, 2); // 5
echo divide(10, 0); // throws exception

4 - Global Handler

set_exception_handler(function (Throwable $e) {
    http_response_code(500);
    error_log($e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
    echo "Something went wrong. Please try again later.";
});

Note: In production, never show exception messages or stack traces to users — they reveal implementation details and file paths that attackers can exploit. Log them server-side instead.

-Tip-