CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-fs

Python's filesystem abstraction layer providing a unified interface for working with different types of filesystems

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

error-handling.mddocs/

Error Handling

Comprehensive exception hierarchy providing specific error types for different filesystem operation failures. PyFileSystem2's error handling enables robust applications by providing detailed information about failure conditions.

Capabilities

Base Exception Classes

Root exception classes that define the error hierarchy structure.

class FSError(Exception):
    """
    Base class for all filesystem errors.
    
    All PyFileSystem2 exceptions inherit from this class, allowing
    applications to catch all filesystem-related errors with a single
    except clause.
    """
    
    def __init__(self, msg: str = None, details: Dict[str, Any] = None) -> None:
        """
        Create filesystem error.

        Parameters:
        - msg: str, error message
        - details: Dict[str, Any], additional error details
        """

class CreateFailed(FSError):
    """Failed to create a resource (file or directory)."""
    pass

class ResourceError(FSError):
    """Base class for resource-related errors."""
    
    def __init__(self, path: str, msg: str = None, details: Dict[str, Any] = None) -> None:
        """
        Create resource error.

        Parameters:
        - path: str, path that caused the error
        - msg: str, error message
        - details: Dict[str, Any], additional error details
        """

Resource Existence Errors

Errors related to resource existence and conflicts.

class ResourceNotFound(ResourceError):
    """
    Resource (file or directory) was not found.
    
    Raised when attempting to access a resource that doesn't exist.
    """
    pass

class ResourceExists(ResourceError):
    """
    Resource already exists when it shouldn't.
    
    Raised when attempting to create a resource that already exists
    and overwrite is not allowed.
    """
    pass

class DirectoryExists(ResourceExists):
    """
    Directory already exists.
    
    Raised when attempting to create a directory that already exists.
    """
    pass

class FileExists(ResourceExists):
    """
    File already exists.
    
    Raised when attempting to create a file that already exists.
    """
    pass

Resource Type Errors

Errors when the wrong resource type is encountered.

class DirectoryExpected(ResourceError):
    """
    Expected a directory but found a file.
    
    Raised when a directory operation is attempted on a file.
    """
    pass

class FileExpected(ResourceError):
    """
    Expected a file but found a directory.
    
    Raised when a file operation is attempted on a directory.
    """
    pass

Permission and Access Errors

Errors related to filesystem permissions and access rights.

class PermissionDenied(ResourceError):
    """
    Permission denied for filesystem operation.
    
    Raised when the current user lacks sufficient permissions
    to perform the requested operation.
    """
    pass

class DirectoryNotEmpty(ResourceError):
    """
    Directory is not empty when it should be.
    
    Raised when attempting to remove a directory that contains files
    or subdirectories.
    """
    pass

System and Network Errors

Errors related to system resources and network connectivity.

class RemoteConnectionError(FSError):
    """
    Failed to connect to remote filesystem.
    
    Raised when network filesystems (FTP, etc.) cannot establish
    or maintain a connection.
    """
    pass

class InsufficientStorage(FSError):
    """
    Insufficient storage space available.
    
    Raised when a write operation fails due to lack of available
    storage space.
    """
    pass

class FilesystemClosed(FSError):
    """
    Filesystem has been closed.
    
    Raised when attempting to perform operations on a closed filesystem.
    """
    pass

Operation Errors

Errors related to specific filesystem operations.

class OperationFailed(FSError):
    """
    Generic operation failure.
    
    Raised when a filesystem operation fails for reasons not covered
    by more specific exception types.
    """
    pass

class OperationTimeout(FSError):
    """
    Operation timed out.
    
    Raised when a filesystem operation takes longer than the specified
    timeout period.
    """
    pass

class Unsupported(FSError):
    """
    Operation not supported by this filesystem.
    
    Raised when attempting an operation that the filesystem
    implementation doesn't support.
    """
    pass

class CrossDeviceError(FSError):
    """
    Cross-device operation not supported.
    
    Raised when attempting to move files across different filesystems
    or devices where atomic operations are not possible.
    """
    pass

Path and URL Errors

Errors related to path validation and URL parsing.

class IllegalBackReference(FSError):
    """
    Illegal back reference in path.
    
    Raised when a path contains '..' components that would escape
    the filesystem root.
    """
    pass

class InvalidPath(FSError):
    """
    Path is invalid for this filesystem.
    
    Raised when a path contains characters or patterns not supported
    by the filesystem.
    """
    pass

class InvalidCharsInPath(InvalidPath):
    """
    Path contains invalid characters.
    
    Raised when a path contains characters that are not allowed
    by the filesystem (e.g., null bytes, control characters).
    """
    pass

class NoSysPath(FSError):
    """
    No system path available for resource.
    
    Raised when getsyspath() is called on a filesystem that doesn't
    map to system paths (e.g., memory filesystems, archives).
    """
    pass

class NoURL(FSError):
    """
    No URL available for resource.
    
    Raised when geturl() is called on a filesystem that doesn't
    support URLs for resources.
    """
    pass

Opener Errors

Errors related to filesystem opening and URL parsing.

class OpenerError(FSError):
    """Base class for opener-related errors."""
    pass

class UnsupportedProtocol(OpenerError):
    """
    Protocol not supported by any opener.
    
    Raised when attempting to open a filesystem with a URL scheme
    that no registered opener can handle.
    """
    pass

class ParseError(OpenerError):
    """
    Failed to parse filesystem URL.
    
    Raised when a filesystem URL cannot be parsed into valid components.
    """
    pass

Usage Examples

Basic error handling:

from fs import open_fs
from fs.errors import FSError, ResourceNotFound, PermissionDenied

try:
    fs = open_fs('.')
    content = fs.readtext('nonexistent.txt')
except ResourceNotFound as e:
    print(f"File not found: {e.path}")
except PermissionDenied as e:
    print(f"Permission denied: {e.path}")
except FSError as e:
    print(f"Filesystem error: {e}")

Handling specific error types:

from fs import open_fs  
from fs.errors import DirectoryExists, FileExists, DirectoryExpected

fs = open_fs('.')

# Handle directory creation errors
try:
    fs.makedir('new_directory')
except DirectoryExists:
    print("Directory already exists")
except FSError as e:
    print(f"Failed to create directory: {e}")

# Handle file vs directory confusion
try:
    fs.listdir('some_file.txt')
except DirectoryExpected:
    print("Expected directory, got file")
except ResourceNotFound:
    print("Path doesn't exist")

Network filesystem error handling:

from fs import open_fs
from fs.errors import RemoteConnectionError, OperationTimeout

try:
    ftp_fs = open_fs('ftp://user:pass@example.com/')
    files = ftp_fs.listdir('/')
except RemoteConnectionError as e:
    print(f"Failed to connect to FTP server: {e}")
except OperationTimeout as e:
    print(f"FTP operation timed out: {e}")
except FSError as e:
    print(f"FTP filesystem error: {e}")

Comprehensive error handling for file operations:

from fs import open_fs
from fs.errors import (
    ResourceNotFound, ResourceExists, PermissionDenied,
    DirectoryExpected, FileExpected, InsufficientStorage,
    FilesystemClosed
)

def safe_copy_file(src_fs, src_path, dst_fs, dst_path):
    """Safely copy file with comprehensive error handling."""
    try:
        # Check if source exists and is a file
        if not src_fs.exists(src_path):
            raise ResourceNotFound(src_path)
        if not src_fs.isfile(src_path):
            raise FileExpected(src_path)
        
        # Check if destination already exists
        if dst_fs.exists(dst_path):
            raise ResourceExists(dst_path)
        
        # Perform the copy
        src_fs.copy(src_path, dst_fs, dst_path)
        return True
        
    except ResourceNotFound as e:
        print(f"Source file not found: {e.path}")
    except FileExpected as e:
        print(f"Source is not a file: {e.path}")
    except ResourceExists as e:
        print(f"Destination already exists: {e.path}")
    except PermissionDenied as e:
        print(f"Permission denied: {e.path}")
    except InsufficientStorage as e:
        print(f"Not enough storage space: {e}")
    except FilesystemClosed as e:
        print(f"Filesystem is closed: {e}")
    except FSError as e:
        print(f"Copy failed: {e}")
    
    return False

Error details and debugging:

from fs import open_fs
from fs.errors import FSError

try:
    fs = open_fs('invalid://bad-url')
except FSError as e:
    print(f"Error message: {e}")
    print(f"Error type: {type(e).__name__}")
    
    # Some errors include additional details
    if hasattr(e, 'details') and e.details:
        print(f"Error details: {e.details}")
    
    # Resource errors include the problematic path
    if hasattr(e, 'path'):
        print(f"Path: {e.path}")

Types

from typing import Dict, Any, Optional

# Error details dictionary type
ErrorDetails = Dict[str, Any]

# Common error attributes
class FSError(Exception):
    msg: Optional[str]
    details: Optional[ErrorDetails]

class ResourceError(FSError):
    path: str

Install with Tessl CLI

npx tessl i tessl/pypi-fs

docs

core-operations.md

error-handling.md

file-operations.md

filesystem-management.md

filesystem-types.md

index.md

path-operations.md

tile.json