How can a website handle a "Error 500" when unable to connect to the database?

When a website encounters an "Error 500" due to being unable to connect to the database, it is essential to handle this error gracefully by displaying a custom error message to the user. One way to address this issue is by using try-catch blocks in your PHP code to catch any exceptions thrown when connecting to the database. Within the catch block, you can set the HTTP response code to 500 and display an error message to the user.

try {
    // Attempt to connect to the database
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
} catch (PDOException $e) {
    // Handle database connection error
    http_response_code(500);
    echo "Error connecting to the database. Please try again later.";
    exit;
}