Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions libp2p/bitswap/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
InvalidBlockError,
BlockTooLargeError,
MessageTooLargeError,
TimeoutError,
BitswapTimeoutError,
BlockNotFoundError,
BlockUnavailableError,
InvalidCIDError,
Expand Down Expand Up @@ -57,7 +57,7 @@
"InvalidBlockError",
"BlockTooLargeError",
"MessageTooLargeError",
"TimeoutError",
"BitswapTimeoutError",
"BlockNotFoundError",
"BlockUnavailableError",
"InvalidCIDError",
Expand Down
2 changes: 1 addition & 1 deletion libp2p/bitswap/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
BlockNotFoundError,
BlockTooLargeError,
MessageTooLargeError,
TimeoutError as BitswapTimeoutError,
BitswapTimeoutError,
)
from .messages import create_message, create_wantlist_entry
from .pb.bitswap_pb2 import Message
Expand Down
10 changes: 7 additions & 3 deletions libp2p/bitswap/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
Bitswap protocol errors.
"""

from libp2p.exceptions import (
ProtocolError,
)

class BitswapError(Exception):

class BitswapError(ProtocolError):
"""Base exception for Bitswap errors."""

pass
Expand All @@ -27,8 +31,8 @@ class MessageTooLargeError(BitswapError):
pass


class TimeoutError(BitswapError):
"""Raised when an operation times out."""
class BitswapTimeoutError(BitswapError):
"""Raised when a Bitswap operation times out."""

pass

Expand Down
7 changes: 6 additions & 1 deletion libp2p/crypto/authenticated_encryption.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@
)
import Crypto.Util.Counter as Counter

from libp2p.crypto.exceptions import (
CryptographyError,
)


class InvalidMACException(Exception):
class InvalidMACException(CryptographyError):
"""Raised when MAC validation fails."""
pass


Expand Down
6 changes: 5 additions & 1 deletion libp2p/discovery/rendezvous/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@
Rendezvous protocol error handling.
"""

from libp2p.exceptions import (
DiscoveryError,
)

from .pb.rendezvous_pb2 import Message


class RendezvousError(Exception):
class RendezvousError(DiscoveryError):
"""Base exception for rendezvous protocol errors."""

def __init__(self, status: Message.ResponseStatus.ValueType, message: str = ""):
Expand Down
111 changes: 110 additions & 1 deletion libp2p/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,123 @@


class BaseLibp2pError(Exception):
pass
"""
Base exception for all libp2p errors.

This exception serves as the root of the exception hierarchy,
allowing users to catch all libp2p-specific errors with a single
exception type.

Example::
>>> try:
... # some libp2p operation
... except BaseLibp2pError as e:
... print(f"Libp2p error: {e}")
"""

def __init__(self, message: str = "", *args, **kwargs):
"""
Initialize the exception.

Args:
message: Error message
*args: Additional positional arguments
**kwargs: Additional keyword arguments (e.g., error_code, context)
"""
super().__init__(message, *args)
self.message = message
self.error_code = kwargs.get('error_code')
self.context = kwargs.get('context', {})

def __str__(self) -> str:
"""Return string representation of the error."""
if self.error_code:
return f"[{self.error_code}] {self.message}"
return self.message

def __repr__(self) -> str:
"""Return detailed representation of the error."""
return f"{self.__class__.__name__}(message={self.message!r}, error_code={self.error_code!r})"


class ValidationError(BaseLibp2pError):
"""Raised when something does not pass a validation check."""


class ParseError(BaseLibp2pError):
"""Raised when parsing fails."""
pass


# Intermediate base classes for logical grouping of exceptions

class NetworkError(BaseLibp2pError):
"""
Base exception for network-related errors.

This includes errors related to connections, streams, transport,
and network operations.
"""
pass


class ProtocolError(BaseLibp2pError):
"""
Base exception for protocol-related errors.

This includes errors related to protocol negotiation, protocol
violations, and protocol-specific errors.
"""
pass


class PeerError(BaseLibp2pError):
"""
Base exception for peer-related errors.

This includes errors related to peer store, peer data, peer
addresses, and peer serialization.
"""
pass


class ResourceError(BaseLibp2pError):
"""
Base exception for resource management errors.

This includes errors related to resource limits, resource
allocation, and resource monitoring.
"""
pass


class ServiceError(BaseLibp2pError):
"""
Base exception for service lifecycle errors.

This includes errors related to service management, service
lifecycle, and service operations.
"""
pass


class DiscoveryError(BaseLibp2pError):
"""
Base exception for discovery-related errors.

This includes errors related to peer discovery, rendezvous,
and routing table operations.
"""
pass


class PubsubError(BaseLibp2pError):
"""
Base exception for pubsub-related errors.

This includes errors related to pubsub routers, pubsub
operations, and pubsub protocols.
"""
pass


Expand Down
5 changes: 3 additions & 2 deletions libp2p/network/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from libp2p.exceptions import (
BaseLibp2pError,
NetworkError,
)


class SwarmException(BaseLibp2pError):
class SwarmException(NetworkError):
"""Exception raised by swarm operations."""
pass
13 changes: 11 additions & 2 deletions libp2p/peer/peerdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
PrivateKey,
PublicKey,
)
from libp2p.exceptions import (
PeerError,
)

"""
Latency EWMA Smoothing governs the deacy of the EWMA (the speed at which
Expand Down Expand Up @@ -231,5 +234,11 @@ def is_expired(self) -> bool:
return False


class PeerDataError(KeyError):
"""Raised when a key is not found in peer metadata."""
class PeerDataError(PeerError, KeyError):
"""
Raised when a key is not found in peer metadata.

This exception uses multiple inheritance to maintain compatibility
with code that catches KeyError while also being part of the
libp2p exception hierarchy.
"""
14 changes: 13 additions & 1 deletion libp2p/peer/peerinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,17 @@ def peer_info_from_bytes(data: bytes) -> PeerInfo:
raise InvalidAddrError(f"failed to decode PeerInfo: {e}")


class InvalidAddrError(ValueError):
from libp2p.exceptions import (
PeerError,
)


class InvalidAddrError(PeerError, ValueError):
"""
Raised when an invalid address is encountered.

This exception uses multiple inheritance to maintain compatibility
with code that catches ValueError while also being part of the
libp2p exception hierarchy.
"""
pass
13 changes: 11 additions & 2 deletions libp2p/peer/peerstore.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
PrivateKey,
PublicKey,
)
from libp2p.exceptions import (
PeerError,
)
from libp2p.peer.envelope import Envelope, seal_record
from libp2p.peer.peer_record import PeerRecord

Expand Down Expand Up @@ -574,5 +577,11 @@ def clear_metrics(self, peer_id: ID) -> None:
peer_data.clear_metrics()


class PeerStoreError(KeyError):
"""Raised when peer ID is not found in peer store."""
class PeerStoreError(PeerError, KeyError):
"""
Raised when peer ID is not found in peer store.

This exception uses multiple inheritance to maintain compatibility
with code that catches KeyError while also being part of the
libp2p exception hierarchy.
"""
7 changes: 6 additions & 1 deletion libp2p/peer/persistent/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@
logger = logging.getLogger(__name__)


class SerializationError(Exception):
from libp2p.exceptions import (
PeerError,
)


class SerializationError(PeerError):
"""Raised when serialization or deserialization fails."""


Expand Down
5 changes: 3 additions & 2 deletions libp2p/pubsub/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from libp2p.exceptions import (
BaseLibp2pError,
PubsubError,
)


class PubsubRouterError(BaseLibp2pError):
class PubsubRouterError(PubsubError):
"""Exception raised by pubsub router operations."""
pass


Expand Down
6 changes: 5 additions & 1 deletion libp2p/rcmgr/circuit_breaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
import time
from typing import Any

from libp2p.exceptions import (
ResourceError,
)


class CircuitBreakerState(Enum):
"""Circuit breaker states."""
Expand All @@ -21,7 +25,7 @@ class CircuitBreakerState(Enum):
HALF_OPEN = "half_open"


class CircuitBreakerError(Exception):
class CircuitBreakerError(ResourceError):
"""Exception raised when circuit breaker is open."""

pass
Expand Down
11 changes: 7 additions & 4 deletions libp2p/rcmgr/enhanced_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@

import multiaddr

from libp2p.exceptions import (
ResourceError,
)
from libp2p.peer.id import ID


Expand Down Expand Up @@ -192,7 +195,7 @@ def __str__(self) -> str:
)


class ResourceLimitExceededError(Exception):
class ResourceLimitExceededError(ResourceError):
"""Enhanced exception for resource limit exceeded errors."""

def __init__(
Expand Down Expand Up @@ -266,7 +269,7 @@ def __str__(self) -> str:
return self._build_error_message()


class SystemResourceError(Exception):
class SystemResourceError(ResourceError):
"""Enhanced exception for system resource errors."""

def __init__(
Expand Down Expand Up @@ -332,7 +335,7 @@ def __str__(self) -> str:
return self._build_error_message()


class ConfigurationError(Exception):
class ConfigurationError(ResourceError):
"""Enhanced exception for configuration errors."""

def __init__(
Expand Down Expand Up @@ -389,7 +392,7 @@ def __str__(self) -> str:
return self._build_error_message()


class OperationalError(Exception):
class OperationalError(ResourceError):
"""Enhanced exception for operational errors."""

def __init__(
Expand Down
6 changes: 5 additions & 1 deletion libp2p/rcmgr/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@

from __future__ import annotations

from libp2p.exceptions import (
ResourceError,
)

class ResourceManagerException(Exception):

class ResourceManagerException(ResourceError):
"""Base exception for all resource manager errors."""

def __init__(self, message: str):
Expand Down
Loading
Loading