CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-zeep

A comprehensive Python SOAP client library for consuming SOAP web services with support for SOAP 1.1/1.2, WSSE authentication, and async operations

Overview
Eval results
Files

exception-handling.mddocs/

Exception Handling

Comprehensive exception hierarchy for handling SOAP faults, transport errors, XML parsing issues, and validation failures. Zeep provides detailed error information to help diagnose and handle various failure scenarios.

Capabilities

Base Exception Classes

Foundation exception classes for all zeep-related errors.

class Error(Exception):
    def __init__(self, message: str = ""):
        """
        Base exception for all zeep errors.
        
        Parameters:
        - message: Error description
        """

class ZeepWarning(RuntimeWarning):
    """Warning class for non-fatal zeep issues."""

SOAP and Transport Errors

Exceptions related to SOAP communication and HTTP transport.

class TransportError(Error):
    def __init__(self, message: str = "", status_code: int = 0, content=None):
        """
        HTTP transport error.
        
        Parameters:
        - message: Error description
        - status_code: HTTP status code
        - content: Response content
        """

class Fault(Error):
    def __init__(
        self, 
        message: str, 
        code: str = None, 
        actor: str = None, 
        detail=None, 
        subcodes: list = None
    ):
        """
        SOAP fault response.
        
        Parameters:
        - message: Fault reason/description
        - code: SOAP fault code
        - actor: SOAP fault actor
        - detail: Fault detail element
        - subcodes: SOAP 1.2 fault subcodes
        """

XML Processing Errors

Exceptions for XML parsing and processing issues.

class XMLSyntaxError(Error):
    def __init__(self, *args, content=None, **kwargs):
        """
        XML syntax parsing error.
        
        Parameters:
        - content: XML content that caused the error
        """

class XMLParseError(Error):
    def __init__(self, *args, filename: str = None, sourceline: int = None, **kwargs):
        """
        XML parsing error with location information.
        
        Parameters:
        - filename: Source file name
        - sourceline: Line number where error occurred
        """

class UnexpectedElementError(Error):
    """Unexpected XML element encountered during parsing."""

WSDL Processing Errors

Exceptions related to WSDL document processing and validation.

class WsdlSyntaxError(Error):
    """WSDL document syntax or structure error."""

class LookupError(Error):
    def __init__(self, *args, qname: str = None, item_name: str = None, location: str = None, **kwargs):
        """
        Namespace or element lookup failure.
        
        Parameters:
        - qname: Qualified name that failed lookup
        - item_name: Item name being looked up
        - location: Location context for lookup
        """

class NamespaceError(Error):
    """XML namespace processing error."""

Validation and Schema Errors

Exceptions for XSD validation and schema processing.

class ValidationError(Error):
    def __init__(self, *args, path: list = None, **kwargs):
        """
        XSD validation error with path information.
        
        Parameters:
        - path: List representing path to validation error
        """

class IncompleteMessage(Error):
    """SOAP message is incomplete or malformed."""

class IncompleteOperation(Error):
    """WSDL operation definition is incomplete."""

Security-Related Errors

Exceptions for WS-Security and XML security processing.

class SignatureVerificationFailed(Error):
    """Digital signature verification failed."""

class DTDForbidden(Error):
    def __init__(self, name: str, sysid: str, pubid: str):
        """
        DTD processing forbidden by security settings.
        
        Parameters:
        - name: DTD name
        - sysid: System ID
        - pubid: Public ID
        """

class EntitiesForbidden(Error):
    def __init__(self, name: str, content: str):
        """
        XML entities forbidden by security settings.
        
        Parameters:
        - name: Entity name
        - content: Entity content
        """

Usage Examples

Basic Exception Handling

from zeep import Client
from zeep.exceptions import Error, Fault, TransportError

client = Client('http://example.com/service.wsdl')

try:
    result = client.service.SomeOperation(param='value')
except Fault as fault:
    print(f"SOAP Fault: {fault.message}")
    print(f"Fault Code: {fault.code}")
    if fault.detail:
        print(f"Fault Detail: {fault.detail}")
except TransportError as error:
    print(f"Transport Error: {error.message}")
    print(f"HTTP Status: {error.status_code}")
    print(f"Response: {error.content}")
except Error as error:
    print(f"Zeep Error: {error.message}")

Handling Different Error Types

from zeep import Client
from zeep.exceptions import (
    XMLSyntaxError, XMLParseError, WsdlSyntaxError, 
    ValidationError, TransportError
)

try:
    client = Client('http://example.com/problematic-service.wsdl')
    result = client.service.ComplexOperation(
        complex_param={
            'required_field': 'value',
            'optional_field': None
        }
    )
except WsdlSyntaxError as error:
    print(f"WSDL has syntax errors: {error}")
    # Handle malformed WSDL document
except XMLSyntaxError as error:
    print(f"XML syntax error: {error}")
    if error.content:
        print(f"Problematic content: {error.content[:200]}...")
except XMLParseError as error:
    print(f"XML parsing failed: {error}")
    if error.filename and error.sourceline:
        print(f"Location: {error.filename}:{error.sourceline}")
except ValidationError as error:
    print(f"Validation failed: {error}")
    if error.path:
        path_str = '.'.join(str(p) for p in error.path)
        print(f"Error path: {path_str}")
except TransportError as error:
    if error.status_code == 404:
        print("Service endpoint not found")
    elif error.status_code == 500:
        print("Server error occurred")
    else:
        print(f"HTTP error {error.status_code}: {error.message}")

Security Exception Handling

from zeep import Client, Settings
from zeep.exceptions import DTDForbidden, EntitiesForbidden, SignatureVerificationFailed

# Strict security settings
settings = Settings(
    forbid_dtd=True,
    forbid_entities=True,
    forbid_external=True
)

try:
    client = Client('http://example.com/service.wsdl', settings=settings)
    result = client.service.SecureOperation(param='value')
except DTDForbidden as error:
    print(f"DTD processing blocked: {error}")
    print(f"DTD name: {error.name}, System ID: {error.sysid}")
except EntitiesForbidden as error:
    print(f"XML entities blocked: {error}")
    print(f"Entity name: {error.name}")
except SignatureVerificationFailed as error:
    print(f"Digital signature verification failed: {error}")
    # Handle authentication/integrity failure

Comprehensive Error Handling

import logging
from zeep import Client
from zeep.exceptions import *

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def safe_soap_call(wsdl_url, operation_name, **params):
    """Safely call SOAP operation with comprehensive error handling."""
    
    try:
        client = Client(wsdl_url)
        operation = getattr(client.service, operation_name)
        return operation(**params)
        
    except Fault as fault:
        logger.error(f"SOAP Fault in {operation_name}: {fault.message}")
        if fault.code:
            logger.error(f"Fault code: {fault.code}")
        if fault.detail:
            logger.error(f"Fault detail: {fault.detail}")
        raise
        
    except TransportError as error:
        logger.error(f"Transport error in {operation_name}: {error.message}")
        logger.error(f"HTTP status: {error.status_code}")
        
        if error.status_code >= 500:
            logger.error("Server error - may be temporary")
        elif error.status_code >= 400:
            logger.error("Client error - check request parameters")
            
        raise
        
    except ValidationError as error:
        logger.error(f"Validation error in {operation_name}: {error}")
        if error.path:
            path_str = '.'.join(str(p) for p in error.path)
            logger.error(f"Validation failed at: {path_str}")
        raise
        
    except WsdlSyntaxError as error:
        logger.error(f"WSDL syntax error: {error}")
        logger.error("The WSDL document is malformed")
        raise
        
    except XMLSyntaxError as error:
        logger.error(f"XML syntax error: {error}")
        if error.content:
            logger.debug(f"Problematic XML: {error.content}")
        raise
        
    except LookupError as error:
        logger.error(f"Lookup error in {operation_name}: {error}")
        if error.qname:
            logger.error(f"Failed to find: {error.qname}")
        raise
        
    except Error as error:
        logger.error(f"General zeep error in {operation_name}: {error}")
        raise
        
    except Exception as error:
        logger.error(f"Unexpected error in {operation_name}: {error}")
        raise

# Usage
try:
    result = safe_soap_call(
        'http://example.com/service.wsdl',
        'ComplexOperation',
        param1='value1',
        param2='value2'
    )
    print(f"Success: {result}")
except Error:
    print("SOAP operation failed - see logs for details")

Custom Error Handling with Retry Logic

import time
from zeep import Client
from zeep.exceptions import TransportError, Error

def resilient_soap_call(client, operation_name, max_retries=3, **params):
    """SOAP call with retry logic for transient errors."""
    
    for attempt in range(max_retries + 1):
        try:
            operation = getattr(client.service, operation_name)
            return operation(**params)
            
        except TransportError as error:
            if error.status_code >= 500 and attempt < max_retries:
                wait_time = 2 ** attempt  # Exponential backoff
                print(f"Server error (attempt {attempt + 1}), retrying in {wait_time}s...")
                time.sleep(wait_time)
                continue
            else:
                print(f"Transport error after {attempt + 1} attempts: {error}")
                raise
                
        except Error as error:
            print(f"Non-recoverable error: {error}")
            raise

# Usage
client = Client('http://example.com/service.wsdl')
try:
    result = resilient_soap_call(
        client, 
        'UnreliableOperation',
        max_retries=3,
        param='value'
    )
except Error as e:
    print(f"Operation failed permanently: {e}")

Install with Tessl CLI

npx tessl i tessl/pypi-zeep

docs

client-operations.md

exception-handling.md

index.md

plugin-system.md

transport-settings.md

wsse-security.md

xsd-types.md

tile.json