What are best practices for handling exceptions and error messages when working with database connections in PHP, specifically with PostgreSQL?

When working with database connections in PHP, especially with PostgreSQL, it is important to handle exceptions and error messages properly to ensure smooth operation and effective debugging. One best practice is to use try-catch blocks to catch exceptions and display meaningful error messages to the user or log them for further investigation.

try {
    $pdo = new PDO('pgsql:host=localhost;dbname=mydatabase', 'username', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
    // log the error message for further investigation
}