Input Validation and Error Handling

Input Validation and Error Handling

Input Validation and Error Handling

Aspose.BarCode FOSS for Python validates all input data before encoding. Each symbology has a dedicated InputParser subclass that checks character sets, length constraints, and format rules. When validation fails, the library raises typed exceptions from the BarcodeError hierarchy so callers can distinguish between input problems, encoding failures, and rendering issues.


The InputParser Layer

Every symbology registers an InputParser implementation. When you call BarcodeService.generate(), the parser runs first, producing a NormalizedPayload or raising InvalidInputError if the data is not valid for that symbology.

from aspose_barcode_foss import BarcodeService

service = BarcodeService()

# Valid Code 128 input — passes the Code128InputParser
barcode = service.generate("code128", "VALID-DATA-001")

# Invalid EAN-13 input — too few digits
try:
    barcode = service.generate("ean13", "123")
except Exception as e:
    print(type(e).__name__, e)

Each symbology parser validates different rules:

  • Code128InputParser — checks that all characters are in the ASCII range supported by Code 128 character sets
  • Code39InputParser — validates characters against the Code 39 base or full-ASCII alphabet depending on Code39Options.full_ascii
  • Ean13InputParser — requires exactly 12 or 13 numeric digits (13th is the check digit)
  • Ean8InputParser — requires exactly 7 or 8 numeric digits
  • QrInputParser — validates data against the selected QrEncodeMode (NUMERIC, ALPHANUMERIC, BYTE, or KANJI)
  • UpcaInputParser — requires exactly 11 or 12 numeric digits
  • UpceInputParser — requires exactly 6, 7, or 8 numeric digits with a valid UPC-E pattern

The BarcodeError Hierarchy

All exceptions inherit from BarcodeError, which extends Python’s built-in Exception. The hierarchy allows catch blocks at different levels of specificity:

ExceptionRaised When
BarcodeErrorBase class for all library exceptions
InvalidInputErrorInput data fails validation (wrong characters, wrong length)
EncodingErrorEncoding logic fails after validation passes
RenderingErrorRenderer encounters an error during SVG or PNG output
SymbologyNotFoundErrorThe symbology name is not registered in SymbologyRegistry
UnsupportedCapabilityErrorA requested capability is not available for the symbology
UnsupportedFeatureErrorA feature is defined but not implemented
from aspose_barcode_foss import BarcodeService
from aspose_barcode_foss.errors import (
    BarcodeError,
    InvalidInputError,
    EncodingError,
    SymbologyNotFoundError,
)

service = BarcodeService()

try:
    barcode = service.generate("code128", "TEST-001")
    svg = barcode.to_svg()
except InvalidInputError as e:
    print(f"Input rejected: {e}")
except EncodingError as e:
    print(f"Encoding failed: {e}")
except SymbologyNotFoundError as e:
    print(f"Unknown symbology: {e}")
except BarcodeError as e:
    print(f"Barcode error: {e}")

Validating Symbology Names

SymbologyNotFoundError is raised when BarcodeService.generate() receives a symbology name that is not registered. The SymbologyRegistry resolves names by canonical name or alias, so "code128", "Code128", and "CODE128" all resolve to the same definition.

from aspose_barcode_foss import BarcodeService
from aspose_barcode_foss.errors import SymbologyNotFoundError

service = BarcodeService()

try:
    barcode = service.generate("invalid_type", "data")
except SymbologyNotFoundError as e:
    print(f"Not found: {e}")

Check Digit Validation

EAN-13, EAN-8, UPC-A, and UPC-E symbologies compute check digits automatically. If you pass the full data including a check digit, the parser verifies it against the computed value. The allow_check_digit_input property on Ean13Options and Ean8Options controls this behavior.

from aspose_barcode_foss import BarcodeService
from aspose_barcode_foss import Ean13Options

service = BarcodeService()

# 12 digits — check digit computed automatically
barcode = service.generate("ean13", "590123412345")

# 13 digits — parser verifies the 13th digit matches the computed value
barcode = service.generate(
    "ean13", "5901234123457",
    encode=Ean13Options(allow_check_digit_input=True),
)

Tips and Best Practices

  • Catch InvalidInputError for user-facing input forms where data might not meet symbology requirements
  • Use BarcodeError as a catch-all only when you do not need to distinguish between error types
  • Check the symbology name against the seven supported symbologies (code128, code39, ean13, ean8, qrcode, upca, upce) before calling generate() to avoid SymbologyNotFoundError
  • For QR codes, set encoding_mode explicitly via QrOptions when the data contains non-ASCII characters
  • Let the library compute check digits rather than supplying them manually — this avoids mismatches

Common Issues

IssueCauseFix
InvalidInputError on EAN-13Data has fewer than 12 digits or contains non-numeric charactersSupply exactly 12 or 13 numeric digits
SymbologyNotFoundErrorTypo in symbology name (e.g. "code_128" instead of "code128")Use the canonical name without underscores
EncodingError on Code 39Data contains lowercase letters without full_ascii=TrueSet Code39Options(full_ascii=True)
UnsupportedFeatureErrorCalling a feature that is defined but not yet implementedCheck known_limitations on the symbology profile
InvalidInputError on UPC-AData has more than 12 digitsSupply exactly 11 or 12 numeric digits

FAQ

How do I check if a symbology name is valid before generating?

Use BarcodeService.registry to access the SymbologyRegistry. Call get_definition() and catch SymbologyNotFoundError if the name is not registered.

Can I disable check digit validation for EAN barcodes?

The parser always validates check digits when you supply the full-length input (13 digits for EAN-13, 8 for EAN-8). To avoid validation, supply only the data digits (12 for EAN-13, 7 for EAN-8) and let the library compute the check digit.

What happens if I pass binary data to a 1D barcode symbology?

InvalidInputError is raised. Code 128, Code 39, EAN, and UPC symbologies only accept text data. For binary data, use QR Code with QrEncodeMode.BYTE.

Does the library validate data length for QR codes?

QrInputParser validates that the data fits within the capacity of the requested QR version. If no version is specified, the library selects the smallest version that accommodates the data.


API Reference Summary

Class / MethodDescription
InputParser.parse(data, options)Abstract method — validates and normalizes input into NormalizedPayload
Code128InputParser.parse(data, options)Validates Code 128 input characters
Code39InputParser.parse(data, options)Validates Code 39 base or full-ASCII input
Ean13InputParser.parse(data, options)Validates EAN-13 digit count and check digit
Ean8InputParser.parse(data, options)Validates EAN-8 digit count and check digit
QrInputParser.parse(data, options)Validates QR data against the selected encode mode
UpcaInputParser.parse(data, options)Validates UPC-A digit count
UpceInputParser.parse(data, options)Validates UPC-E digit count and pattern
BarcodeErrorBase exception for the barcode library
InvalidInputErrorRaised for invalid input data
EncodingErrorRaised when encoding fails
RenderingErrorRaised when rendering fails
SymbologyNotFoundErrorRaised for unregistered symbology names
UnsupportedCapabilityErrorRaised for unavailable capabilities
UnsupportedFeatureErrorRaised for unimplemented features

See Also

 English