In PHP, how can error handling be improved to provide more user-friendly feedback when unique constraints are violated?

When unique constraints are violated in PHP, it often results in a generic error message that may not be user-friendly. To improve error handling and provide more informative feedback to users, you can catch the specific exception thrown when a unique constraint is violated and display a custom error message.

try {
    // Your database query that may violate a unique constraint
} catch (PDOException $e) {
    if ($e->errorInfo[1] == 1062) {
        echo "This record violates a unique constraint. Please provide a different value.";
    } else {
        echo "An error occurred: " . $e->getMessage();
    }
}