Error Handling

Comprehensive guide to understanding and handling errors in the Document Template Processing Service.

Table of Contents
  1. HTTP Status Codes
  2. Error Response Format
  3. Error Categories
    1. File Processing Errors
      1. invalid_file_type
      2. missing_file
      3. file_upload_error
      4. image_processing_error
    2. Template Processing Errors
      1. missing_template_data
      2. invalid_json
      3. invalid_json_data
      4. template_syntax_error
      5. undefined_variable
      6. template_runtime_error
      7. template_document_corruption
      8. invalid_request_structure
    3. PDF Conversion Errors
      1. pdf_conversion_timeout
      2. pdf_conversion_failed
      3. gotenberg_connection_error
  4. Debugging Template Issues
    1. Step-by-Step Debugging
    2. Common Error Scenarios
      1. Template Variable Mismatch
      2. Invalid Template Syntax
      3. Data Type Issues
  5. Error Prevention Best Practices
    1. Template Development
    2. Data Validation
    3. Application Integration
    4. Example Error Handling Code
      1. JavaScript/React
      2. Python
  6. Getting Help

HTTP Status Codes

Status Code Description When It Occurs
200 Success Document processed successfully
400 Bad Request Invalid file type, malformed data, or template errors
422 Unprocessable Entity Invalid JSON structure or validation errors
500 Internal Server Error Service errors, Gotenberg issues, or unexpected failures

Error Response Format

All errors return a structured JSON response:

{
  "message": "Human-readable error description",
  "error_type": "machine_readable_error_category",
  "details": {
    "field": "additional_context",
    "suggestion": "how_to_fix_the_issue"
  }
}

Error Categories

File Processing Errors

invalid_file_type

Cause: Non-.docx file uploaded
Status: 400

{
  "message": "Invalid file type. Only .docx files are supported",
  "error_type": "invalid_file_type",
  "details": {
    "provided_filename": "document.pdf",
    "supported_types": [".docx"],
    "requirement": "Upload a Microsoft Word .docx file"
  }
}

missing_file

Cause: No file provided in request
Status: 400

{
  "message": "No file uploaded",
  "error_type": "missing_file",
  "details": {
    "requirement": "A valid .docx file must be uploaded"
  }
}

file_upload_error

Cause: File system or I/O errors during upload
Status: 500

{
  "message": "Failed to save uploaded file: [details]",
  "error_type": "file_upload_error",
  "details": {
    "io_error": "Permission denied",
    "suggestion": "Check file permissions and disk space"
  }
}

image_processing_error

Cause: Invalid image data or processing failures (Enhanced Mode only)
Status: 400

{
  "message": "Failed to process image 'company_logo': Invalid base64 data",
  "error_type": "image_processing_error",
  "details": {
    "image_name": "company_logo",
    "error": "Invalid base64 data",
    "suggestion": "Ensure image data is valid base64 encoded PNG"
  }
}

Template Processing Errors

missing_template_data

Cause: No data parameter provided
Status: 400

{
  "message": "No template data provided. Use either 'data' parameter (legacy) or 'request_data' parameter (enhanced with images)",
  "error_type": "missing_template_data",
  "details": {
    "requirement": "Provide either 'data' (JSON object) or 'request_data' (JSON string)",
    "examples": {
      "legacy": "{\"name\": \"John Doe\"}",
      "enhanced": "{\"template_data\": {\"name\": \"John Doe\"}, \"images\": {}}"
    }
  }
}

invalid_json

Cause: Malformed JSON in data or request_data
Status: 400

{
  "message": "Invalid JSON data: Expecting ',' delimiter: line 2 column 15 (char 16)",
  "error_type": "invalid_json",
  "details": {
    "json_error": "Expecting ',' delimiter: line 2 column 15 (char 16)",
    "line": 2,
    "column": 15,
    "suggestion": "Ensure the data parameter contains valid JSON"
  }
}

invalid_json_data

Cause: Non-serializable data types
Status: 422

{
  "message": "Invalid template data: Object of type datetime is not JSON serializable",
  "error_type": "invalid_json_data",
  "details": {
    "json_error": "Object of type datetime is not JSON serializable",
    "data_type": "dict",
    "suggestion": "Ensure all data values are JSON serializable (strings, numbers, booleans, lists, dicts)"
  }
}

template_syntax_error

Cause: Invalid Jinja2 template syntax
Status: 400

{
  "message": "Template syntax error in template.docx: unexpected 'end of template'",
  "error_type": "template_syntax_error",
  "details": {
    "file": "template.docx",
    "syntax_error": "unexpected 'end of template'",
    "line": 15,
    "suggestion": "Check template for missing {% endif %} or {% endfor %} tags"
  }
}

undefined_variable

Cause: Template references undefined variable or tries to access attributes on dictionary objects
Status: 400

Basic undefined variable:

{
  "message": "Undefined variable in template: 'customer_namme' is undefined",
  "error_type": "undefined_variable",
  "details": {
    "file": "template.docx",
    "undefined_variable": "'customer_namme' is undefined",
    "suggestion": "Check your template variables match the provided data"
  }
}

Dictionary attribute access error (improved in v1.2+):

{
  "message": "Undefined variable in template: 'dict object' has no attribute 'organization'",
  "error_type": "undefined_variable",
  "details": {
    "file": "template.docx",
    "undefined_variable": "'dict object' has no attribute 'organization'",
    "suggestion": "The template is trying to access '.organization' on a dictionary. Use bracket notation like  instead of  or ensure your data structure provides objects with attributes rather than dictionaries."
  }
}

Common Solutions:

  • Check for typos in variable names
  • Ensure all referenced fields exist in your data
  • For nested data access, use either:
    • Object notation: `` (requires object structure)
    • Bracket notation: `` (works with dictionaries)
  • Use default filters for optional fields: ``

template_runtime_error

Cause: Runtime errors during template processing (type errors, division by zero, etc.)
Status: 400

{
  "message": "Template runtime error in template.docx: unsupported operand type(s) for /: 'str' and 'int'",
  "error_type": "template_runtime_error",
  "details": {
    "file": "template.docx",
    "runtime_error": "unsupported operand type(s) for /: 'str' and 'int'",
    "suggestion": "Check data types in template expressions and ensure mathematical operations use numbers"
  }
}

template_document_corruption

Cause: Corrupted or invalid .docx file
Status: 400

{
  "message": "Document corruption detected in template.docx: not a valid docx file",
  "error_type": "template_document_corruption",
  "details": {
    "file": "template.docx",
    "corruption_details": "not a valid docx file",
    "suggestion": "Ensure the file is a valid Microsoft Word .docx document and not corrupted"
  }
}

invalid_request_structure

Cause: Invalid structure in request_data parameter (Enhanced Mode only)
Status: 400

{
  "message": "Invalid request structure: 1 validation error for TemplateRequest template_data field required",
  "error_type": "invalid_request_structure",
  "details": {
    "error": "1 validation error for TemplateRequest template_data field required",
    "suggestion": "Ensure request follows TemplateRequest model structure"
  }
}

PDF Conversion Errors

pdf_conversion_timeout

Cause: Gotenberg conversion takes too long
Status: 500

{
  "message": "PDF conversion timed out after 30 seconds",
  "error_type": "pdf_conversion_timeout",
  "details": {
    "timeout_seconds": 30,
    "suggestion": "Try with a simpler template or check Gotenberg service status"
  }
}

pdf_conversion_failed

Cause: Gotenberg service errors
Status: 500

{
  "message": "PDF conversion failed: Gotenberg service returned error 400",
  "error_type": "pdf_conversion_failed",
  "details": {
    "gotenberg_status": 400,
    "gotenberg_error": "invalid document format",
    "suggestion": "Check document format and Gotenberg service availability"
  }
}

gotenberg_connection_error

Cause: Cannot connect to Gotenberg service
Status: 500

{
  "message": "Cannot connect to Gotenberg service",
  "error_type": "gotenberg_connection_error",
  "details": {
    "connection_error": "Connection refused",
    "gotenberg_url": "http://gotenberg:3000",
    "suggestion": "Ensure Gotenberg service is running and accessible"
  }
}

Debugging Template Issues

Step-by-Step Debugging

  1. Validate JSON Data
    echo '{"name": "test"}' | jq .
    
  2. Test with Minimal Template
    • Create simple template with ``
    • Send minimal data: {"test_var": "Hello"}
  3. Check Template Syntax
    • Ensure all {% if %} have matching {% endif %}
    • Verify loop syntax: {% for item in items %}...{% endfor %}
  4. Validate Variable Names
    • Check spelling and case sensitivity
    • Ensure all template variables exist in data
  5. Test Data Types
    • Numbers for mathematical operations
    • Arrays for loops
    • Strings for text substitution

Common Error Scenarios

Template Variable Mismatch

Template: {{customer_namme}}
Data: {"customer_name": "John"}
Error: template_undefined_error
Fix: Correct spelling in template

Invalid Template Syntax

Template: {% if amount > 100 %}...{% endfor %}
Error: template_syntax_error
Fix: Change {% endfor %} to {% endif %}

Data Type Issues

Template: {{price / quantity}}
Data: {"price": "100.00", "quantity": 2}
Error: template_runtime_error
Fix: Use numbers: {"price": 100.00, "quantity": 2}

Error Prevention Best Practices

Template Development

  1. Use descriptive variable names to avoid typos
  2. Test templates incrementally with simple data first
  3. Validate template syntax before deployment
  4. Include error handling in your application

Data Validation

  1. Validate JSON structure before sending requests
  2. Check data types match template expectations
  3. Handle optional fields with default values
  4. Test with edge cases (empty arrays, null values)

Application Integration

  1. Implement retry logic for temporary failures
  2. Log error responses for debugging
  3. Provide user-friendly error messages
  4. Validate files before upload

Example Error Handling Code

JavaScript/React

try {
  const response = await fetch('/api/v1/process-template-document', {
    method: 'POST',
    body: formData
  });
  
  if (!response.ok) {
    const error = await response.json();
    
    switch (error.error_type) {
      case 'invalid_file_type':
        setError('Please upload a .docx file');
        break;
      case 'template_syntax_error':
        setError(`Template error: ${error.details.suggestion}`);
        break;
      case 'pdf_conversion_failed':
        setError('PDF generation failed. Please try again.');
        break;
      default:
        setError(error.message);
    }
    return;
  }
  
  // Handle success
  const pdfBlob = await response.blob();
  // ... download logic
  
} catch (error) {
  setError('Network error. Please check your connection.');
}

Python

import requests

try:
    response = requests.post(
        'http://localhost:8000/api/v1/process-template-document',
        files={'file': open('template.docx', 'rb')},
        data={'data': json.dumps(template_data)},
        timeout=30
    )
    
    if response.status_code == 200:
        with open('output.pdf', 'wb') as f:
            f.write(response.content)
    else:
        error = response.json()
        print(f"Error: {error['message']}")
        print(f"Type: {error['error_type']}")
        if 'suggestion' in error.get('details', {}):
            print(f"Suggestion: {error['details']['suggestion']}")
            
except requests.exceptions.Timeout:
    print("Request timed out. Please try again.")
except requests.exceptions.ConnectionError:
    print("Cannot connect to service. Check if it's running.")
except Exception as e:
    print(f"Unexpected error: {e}")

Getting Help

If you encounter errors not covered in this guide:

  1. Check the service logs for additional details
  2. Verify your template syntax using online Jinja2 testers
  3. Test with minimal examples to isolate the issue
  4. Review the API documentation for correct usage patterns
  5. Check Gotenberg service status if PDF conversion fails

For image-specific errors, see the Image Support Guide troubleshooting section.


Copyright © 2024 Etherisc GmbH. Distributed under the MIT license.