CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-py-asterisk

Asterisk Manager API Python interface for programmatically controlling and monitoring Asterisk PBX systems

Pending
Overview
Eval results
Files

exceptions.mddocs/

Exception Handling

Comprehensive exception classes for different error conditions in Manager API communication, authentication, action execution, and configuration management.

Capabilities

Base Exception Classes

BaseException

class BaseException(Exception):
    """
    Base class for all py-Asterisk exceptions.
    
    Attributes:
        _prefix: Error message prefix for this exception type
        _error: Specific error message
    """
    
    def __init__(error: str):
        """Initialize with specific error message."""
    
    def __str__() -> str:
        """Return formatted error message: '{_prefix}: {_error}'"""

Manager API Exceptions

Authentication Errors

class AuthenticationFailure(BaseException):
    """
    Raised when authentication to the PBX instance fails.
    Usually indicates incorrect username/password or insufficient privileges.
    """

Communication Errors

class CommunicationError(BaseException):
    """
    Raised when the PBX responds in an unexpected manner.
    Indicates protocol-level communication problems.
    """
    
    def __init__(packet: dict, msg: str = None):
        """
        Initialize with problematic packet and optional message.
        
        Args:
            packet: The Manager API packet that caused the error
            msg: Additional error description
        """

Connection Errors

class GoneAwayError(BaseException):
    """
    Raised when the Manager connection becomes closed unexpectedly.
    Usually indicates network issues or Asterisk restart.
    """

Action Errors

class ActionFailed(BaseException):
    """
    Raised when a PBX action fails.
    The Manager API returned an error response for the requested action.
    """

class PermissionDenied(BaseException):
    """
    Raised when connection is not permitted to perform requested action.
    User lacks necessary Manager API privileges.
    """

Internal Errors

class InternalError(BaseException):
    """
    Raised when an error occurs within a Manager object.
    Indicates a problem in the py-Asterisk library itself.
    """

Configuration Exceptions

class ConfigurationError(BaseException):
    """
    Raised when there is a problem with configuration.
    Could be missing files, invalid format, or bad values.
    """

Utility Exceptions

class SubscriptionError(BaseException):
    """
    Raised when attempt to register the same (event, handler) tuple twice.
    Prevents duplicate event subscriptions.
    """

class ArgumentsError(BaseException):
    """
    Raised for bad command-line arguments in CLI functions.
    """

Usage Examples

Basic Exception Handling

from Asterisk.Manager import Manager, AuthenticationFailure, CommunicationError

try:
    manager = Manager(('127.0.0.1', 5038), 'baduser', 'wrongpass')
except AuthenticationFailure as e:
    print(f"Login failed: {e}")
    # Handle authentication error - check credentials
except CommunicationError as e:
    print(f"Communication problem: {e}")
    # Handle protocol errors - check Asterisk configuration

Comprehensive Error Handling

from Asterisk.Manager import (
    Manager, AuthenticationFailure, CommunicationError, 
    GoneAwayError, ActionFailed, PermissionDenied
)

def robust_manager_operation():
    manager = None
    try:
        # Connect
        manager = Manager(('127.0.0.1', 5038), 'admin', 'secret')
        
        # Execute action
        result = manager.ShowChannels()
        return result
        
    except AuthenticationFailure:
        print("Authentication failed - check username/password")
        return None
        
    except PermissionDenied:
        print("Permission denied - user needs 'call' privilege")
        return None
        
    except ActionFailed as e:
        print(f"Action failed: {e}")
        return None
        
    except CommunicationError as e:
        print(f"Communication error: {e}")
        # Could retry with exponential backoff
        return None
        
    except GoneAwayError:
        print("Connection lost - Asterisk may have restarted")
        # Could attempt reconnection
        return None
        
    finally:
        if manager:
            try:
                manager.Logoff()
            except:
                pass  # Connection may already be dead

Channel Operation Error Handling

from Asterisk.Manager import Manager, ActionFailed

manager = Manager(('127.0.0.1', 5038), 'admin', 'secret')

try:
    # Try to hang up a channel
    channel = manager.get_channel('SIP/1001-00000001')
    channel.Hangup()
    
except ActionFailed as e:
    if 'No such channel' in str(e):
        print("Channel already hung up or doesn't exist")
    else:
        print(f"Hangup failed: {e}")

Configuration Error Handling

from Asterisk.Config import Config, ConfigurationError

try:
    config = Config('/etc/asterisk/py-asterisk.conf')
except ConfigurationError as e:
    print(f"Configuration error: {e}")
    # Fall back to default configuration or prompt user
    config = None

Event Subscription Error Handling

from Asterisk.Util import EventCollection, SubscriptionError

events = EventCollection()

def my_handler(event):
    print(f"Got event: {event}")

try:
    events.subscribe('Hangup', my_handler)
    events.subscribe('Hangup', my_handler)  # Duplicate!
except SubscriptionError as e:
    print(f"Subscription error: {e}")
    # Handler already subscribed

CLI Error Handling

from Asterisk.CLI import command_line, ArgumentsError

try:
    command_line(['py-asterisk', 'action'])  # Missing action name
except ArgumentsError as e:
    print(f"Invalid arguments: {e}")
    # Show usage information

Error Categories

Network/Connection Errors

  • CommunicationError: Protocol-level problems
  • GoneAwayError: Connection lost
  • AuthenticationFailure: Login failed

Permission/Access Errors

  • PermissionDenied: Insufficient Manager API privileges
  • ActionFailed: Action not allowed or failed

Configuration Errors

  • ConfigurationError: Config file problems

Usage Errors

  • ArgumentsError: Bad CLI arguments
  • SubscriptionError: Duplicate event subscriptions

Internal Errors

  • InternalError: Library bugs or unexpected states

Install with Tessl CLI

npx tessl i tessl/pypi-py-asterisk

docs

channel-management.md

cli-utilities.md

configuration.md

exceptions.md

index.md

manager-api.md

tile.json