Skip to main content

Error Handling

PDFDancer provides detailed exception handling to help you identify and resolve issues quickly. All exceptions include descriptive error messages and context.


Exception Hierarchy

All exceptions inherit from PdfDancerException:

  • PdfDancerException - Base exception for all PDFDancer errors
    • ValidationException - Client-side validation errors (missing token, invalid coordinates, etc.)
    • FontNotFoundException - Font not found on the service
    • HttpClientException - HTTP transport or server errors
    • SessionException - Session creation or management failures
from pdfdancer.exceptions import (
PdfDancerException,
ValidationException,
FontNotFoundException,
HttpClientException,
SessionException
)

Handling Validation Errors

from pdfdancer import PDFDancer
from pdfdancer.exceptions import ValidationException

try:
# Missing required token
with PDFDancer.open("document.pdf") as pdf:
pass
except ValidationException as e:
print(f"Validation error: {e}")
# Output: "Validation error: API token is required"

try:
# Invalid coordinates
with PDFDancer.open("document.pdf", token="valid-token") as pdf:
pdf.new_paragraph() \
.text("Test") \
.font("Helvetica", 12) \
.at(page_number=-1, x=100, y=500) \
.add()
except ValidationException as e:
print(f"Validation error: {e}")
# Output: "Validation error: Page number must be positive"

Handling Font Errors

from pdfdancer import PDFDancer
from pdfdancer.exceptions import FontNotFoundException

try:
with PDFDancer.open("document.pdf") as pdf:
pdf.new_paragraph() \
.text("Hello") \
.font("NonExistentFont", 12) \
.at(page_number=1, x=100, y=500) \
.add()
except FontNotFoundException as e:
print(f"Font not found: {e}")
# Fallback to default font
with PDFDancer.open("document.pdf") as pdf:
pdf.new_paragraph() \
.text("Hello") \
.font("Helvetica", 12) \
.at(page_number=1, x=100, y=500) \
.add()
pdf.save("output.pdf")

Handling HTTP and Session Errors

from pdfdancer import PDFDancer
from pdfdancer.exceptions import (
HttpClientException,
SessionException,
PdfDancerException
)

try:
with PDFDancer.open(
"document.pdf",
token="invalid-token",
base_url="https://api.pdfdancer.com"
) as pdf:
pdf.save("output.pdf")

except SessionException as e:
print(f"Session error: {e}")
# Session creation failed, possibly due to invalid token

except HttpClientException as e:
print(f"HTTP error: {e}")
# Network or server error

except PdfDancerException as e:
print(f"Unexpected error: {e}")
# Catch-all for other PDFDancer errors

Complete Error Handling Pattern

from pdfdancer import PDFDancer, Color
from pdfdancer.exceptions import (
ValidationException,
FontNotFoundException,
HttpClientException,
SessionException,
PdfDancerException
)

def process_pdf(input_path: str, output_path: str) -> bool:
"""
Process a PDF with comprehensive error handling.

Returns True on success, False on failure.
"""
try:
with PDFDancer.open(input_path) as pdf:
# Find and edit paragraphs
paragraphs = pdf.page(1).select_paragraphs_starting_with("Invoice")

if paragraphs:
paragraphs[0].edit() \
.replace("PAID") \
.color(Color(0, 128, 0)) \
.apply()

# Add watermark
pdf.new_paragraph() \
.text("CONFIDENTIAL") \
.font("Helvetica-Bold", 48) \
.color(Color(200, 200, 200)) \
.at(page_number=1, x=150, y=400) \
.add()

pdf.save(output_path)
return True

except ValidationException as e:
print(f"Validation failed: {e}")
print("Check your input parameters and try again.")
return False

except FontNotFoundException as e:
print(f"Font error: {e}")
print("Using fallback font...")
# Retry with fallback font
try:
with PDFDancer.open(input_path) as pdf:
pdf.new_paragraph() \
.text("CONFIDENTIAL") \
.font("Helvetica", 48) \
.color(Color(200, 200, 200)) \
.at(page_number=1, x=150, y=400) \
.add()
pdf.save(output_path)
return True
except Exception as retry_error:
print(f"Retry failed: {retry_error}")
return False

except SessionException as e:
print(f"Session error: {e}")
print("Check your API token and network connection.")
return False

except HttpClientException as e:
print(f"HTTP error: {e}")
print("The API server may be unavailable. Try again later.")
return False

except PdfDancerException as e:
print(f"PDFDancer error: {e}")
return False

except Exception as e:
print(f"Unexpected error: {e}")
return False


# Usage
success = process_pdf("invoice.pdf", "processed_invoice.pdf")
if success:
print("PDF processed successfully!")
else:
print("PDF processing failed.")

Common Error Scenarios

Missing API Token

# Error: ValidationException - API token is required
# Solution: Set PDFDANCER_TOKEN environment variable or pass token explicitly

import os
os.environ['PDFDANCER_TOKEN'] = 'your-token'

# Or pass explicitly
with PDFDancer.open("doc.pdf", token="your-token") as pdf:
pass

File Not Found

from pathlib import Path

pdf_path = Path("document.pdf")

if not pdf_path.exists():
print(f"Error: File {pdf_path} not found")
else:
with PDFDancer.open(pdf_path) as pdf:
pdf.save("output.pdf")

Network Timeout

# Increase timeout for large PDFs or slow connections
with PDFDancer.open(
"large-document.pdf",
timeout=120 # 120 seconds
) as pdf:
pdf.save("output.pdf")

Next Steps

  • Advanced – Learn advanced patterns and optimization techniques
  • Examples – See complete working examples with error handling