What are some best practices for handling errors and displaying them in PHP scripts to avoid issues like "Die Webseite kann nicht angezeigt werden" or a white page?

When errors occur in PHP scripts, it is important to handle them gracefully to avoid displaying generic error messages like "Die Webseite kann nicht angezeigt werden" or a white page, which can confuse users and potentially expose sensitive information. One best practice is to use try-catch blocks to catch exceptions and display a user-friendly error message instead. Additionally, enabling error reporting and logging errors to a file can help in debugging issues without exposing them to users.

<?php
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Set a custom error handler function
function customErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "An error occurred. Please try again later.";
    error_log("Error: $errstr in $errfile on line $errline");
}

set_error_handler("customErrorHandler");

// Example code that may throw an error
$file = 'non_existent_file.txt';

try {
    $contents = file_get_contents($file);
    echo $contents;
} catch (Exception $e) {
    echo "An error occurred while processing your request.";
    error_log("Exception: " . $e->getMessage());
}
?>