Exceptions API Reference

This page documents all exception classes in gntplib.

Exception Hierarchy

All gntplib exceptions inherit from GNTPError:

GNTPError
├── GNTPConnectionError
├── GNTPAuthenticationError
├── GNTPEncryptionError
├── GNTPProtocolError
├── GNTPResponseError
├── GNTPResourceError
└── GNTPValidationError

Base Exception

exception GNTPError(message, details=None, original_message=None)[source]

Bases: Exception

Base exception class for all GNTP-related errors.

This exception is raised for general GNTP protocol errors, connection issues, and any other errors specific to GNTP operations.

message

Primary error message

details

Optional additional details about the error

original_message

Original GNTP message that caused the error (if applicable)

Attributes

message

Primary error message.

details

Optional additional details.

original_message

Original GNTP message that caused error (if applicable).

Example

from gntplib.exceptions import GNTPError

try:
    publisher.register()
except GNTPError as e:
    print(f"Error: {e}")
    if e.details:
        print(f"Details: {e.details}")
__init__(message, details=None, original_message=None)[source]

Initialize GNTP error with message and optional details.

Parameters:
  • message (str) – Primary error description

  • details (str | None) – Additional context or information

  • original_message (bytes | None) – The original GNTP message that caused the error

__str__()[source]

Return string representation of the error.

Specific Exceptions

Connection Errors

exception GNTPConnectionError(message, details=None, original_message=None)[source]

Bases: GNTPError

Raised when connection to GNTP server fails.

This includes timeout errors, refused connections, and network issues.

Raised when connection to GNTP server fails.

Common causes:

  • Server not running

  • Wrong host/port

  • Network issues

  • Firewall blocking connection

Example

from gntplib.exceptions import GNTPConnectionError
import time

max_retries = 3
for attempt in range(max_retries):
    try:
        publisher.register()
        break
    except GNTPConnectionError as e:
        print(f"Attempt {attempt + 1} failed: {e}")
        if attempt < max_retries - 1:
            time.sleep(2)

Authentication Errors

exception GNTPAuthenticationError(message, details=None, original_message=None)[source]

Bases: GNTPError

Raised when authentication with GNTP server fails.

This occurs when password/key authentication is rejected.

Raised when authentication fails.

Common causes:

  • Wrong password

  • Incompatible hash algorithm

  • Server doesn’t require/support authentication

Example

from gntplib.exceptions import GNTPAuthenticationError

try:
    publisher = Publisher(
        'App',
        events,
        password='wrong-password'
    )
    publisher.register()
except GNTPAuthenticationError as e:
    print(f"Authentication failed: {e}")

Encryption Errors

exception GNTPEncryptionError(message, details=None, original_message=None)[source]

Bases: GNTPError

Raised when encryption/decryption operations fail.

This includes cipher initialization errors and key size mismatches.

Raised when encryption operations fail.

Common causes:

  • PyCryptodome not installed

  • Key size mismatch

  • Invalid cipher parameters

Example

from gntplib.exceptions import GNTPEncryptionError
from gntplib.keys import MD5
from gntplib.ciphers import AES

try:
    # MD5 (128-bit) too small for AES (192-bit)
    publisher = Publisher(
        'App',
        events,
        password='secret',
        key_hashing=MD5,
        encryption=AES
    )
except GNTPEncryptionError as e:
    print(f"Encryption error: {e}")

Protocol Errors

exception GNTPProtocolError(message, details=None, original_message=None)[source]

Bases: GNTPError

Raised when GNTP protocol violations are detected.

This includes malformed messages, unsupported versions, and invalid headers.

Raised when GNTP protocol violations detected.

Common causes:

  • Malformed messages

  • Unsupported version

  • Invalid headers

Example

from gntplib.exceptions import GNTPProtocolError
from gntplib.requests import parse_response

try:
    response = parse_response(malformed_message)
except GNTPProtocolError as e:
    print(f"Protocol error: {e}")

Response Errors

exception GNTPResponseError(error_code, error_description, original_message=None)[source]

Bases: GNTPError

Raised when GNTP server returns an error response.

error_code

The error code from the server

error_description

Human-readable error description from server

Raised when server returns error response.

Additional Attributes

error_code

Error code from server.

error_description

Human-readable error from server.

Example

from gntplib.exceptions import GNTPResponseError

try:
    publisher.publish('unknown_event', 'Title', 'Text')
except GNTPResponseError as e:
    print(f"Server error: {e.error_code}")
    print(f"Description: {e.error_description}")
__init__(error_code, error_description, original_message=None)[source]

Initialize response error with server error details.

Parameters:
  • error_code (str) – Error code from GNTP server

  • error_description (str) – Error description from GNTP server

  • original_message (bytes | None) – Original response message

Resource Errors

exception GNTPResourceError(message, details=None, original_message=None)[source]

Bases: GNTPError

Raised when resource operations fail.

This includes failures in fetching remote resources or processing binary data.

Raised when resource operations fail.

Common causes:

  • Failed to fetch remote resource

  • Invalid resource data

  • File not found

Example

from gntplib.exceptions import GNTPResourceError
from gntplib import Resource

try:
    icon = Resource.from_file('missing.png')
except GNTPResourceError as e:
    print(f"Resource error: {e}")

Validation Errors

exception GNTPValidationError(message, details=None, original_message=None)[source]

Bases: GNTPError

Raised when input validation fails.

This includes invalid parameter values, missing required fields, etc.

Raised when input validation fails.

Common causes:

  • Empty required fields

  • Invalid parameter values

  • Type mismatches

Example

from gntplib.exceptions import GNTPValidationError
from gntplib import Event, Publisher

try:
    # Empty name not allowed
    event = Event('')
except GNTPValidationError as e:
    print(f"Validation error: {e}")

try:
    # No events defined
    publisher = Publisher('App', [])
except GNTPValidationError as e:
    print(f"Validation error: {e}")

Error Handling Best Practices

Catch Specific Exceptions

from gntplib.exceptions import (
    GNTPConnectionError,
    GNTPAuthenticationError,
    GNTPError
)

try:
    publisher.register()
    publisher.publish('event', 'Title', 'Message')

except GNTPConnectionError:
    # Handle connection issues
    log.error("Cannot connect to GNTP server")

except GNTPAuthenticationError:
    # Handle auth issues
    log.error("Authentication failed")

except GNTPError as e:
    # Catch-all for other GNTP errors
    log.error(f"GNTP error: {e}")

except Exception as e:
    # Unexpected errors
    log.exception("Unexpected error")

Retry Logic

import time
from gntplib.exceptions import GNTPConnectionError

def send_with_retry(publisher, *args, max_retries=3, **kwargs):
    """Send notification with automatic retry."""
    for attempt in range(max_retries):
        try:
            publisher.publish(*args, **kwargs)
            return True
        except GNTPConnectionError:
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)  # Exponential backoff
                continue
            raise
    return False

Graceful Degradation

from gntplib.exceptions import GNTPError

def notify_user(title, message):
    """Notify with fallback to console."""
    try:
        publisher.publish('event', title, message)
    except GNTPError:
        # Fallback to console
        print(f"[{title}] {message}")

See Also