Error Handling & Exceptions
Relevant source files
The following files were used as context for generating this wiki page:
The python-multipart library employs a structured exception hierarchy to manage errors encountered during the streaming parsing of multipart, querystring, and octet-stream data. These exceptions are designed to provide granular feedback regarding the nature of the failure, such as protocol violations, size limit breaches, or decoding issues.
Error handling is integrated into the state machines of the individual parsers, ensuring that malformed input is caught immediately upon ingestion. This is particularly critical in streaming contexts where partial data must be validated against RFC specifications (e.g., RFC 2046, RFC 7578) and user-defined security constraints.
Exception Hierarchy
All custom exceptions within the library inherit from a common base, facilitating broad or specific error catching by the consumer.
Class Relationship Diagram
The following diagram illustrates the inheritance structure of the exceptions used in the project.
Core Exception Classes
| Exception Class | Description | Attributes |
|---|---|---|
MultipartError | The base class for all exceptions in the library. | N/A |
FormParserError | Raised for general errors during form parsing, such as missing boundaries or unknown content types. | N/A |
MultipartParseError | Raised when the MultipartParser encounters malformed multipart data. | offset: The byte index in the current chunk where the error occurred. |
QuerystringParseError | Raised when the QuerystringParser encounters malformed key-value pairs in strict mode. | offset: The byte index in the current chunk where the error occurred. |
DecodeError | Raised when decoders (Base64 or Quoted-Printable) fail to process data. | N/A |
FileError | Raised when there are issues creating or writing to temporary files on disk. | N/A |
Sources: python_multipart/exceptions.py:1-40, python_multipart/multipart.py:1044-1050
Parsing Errors and Validation
Errors are frequently raised during the write() phase of parsing when input data violates expected states or limits.
Multipart Validation Logic
The MultipartParser performs several checks during initialization and data ingestion:
- Boundary Length: Validates that the boundary does not exceed
MAX_BOUNDARY_LENGTH(256 bytes). - Header Limits: Enforces
MAX_HEADER_COUNTandMAX_HEADER_SIZEto prevent resource exhaustion attacks. - State Transitions: Raises
MultipartParseErrorif expected delimiters (CR, LF, Colons) are missing or if invalid characters are found in header tokens.
Querystring Strict Parsing
The QuerystringParser can operate in a strict_parsing mode. In this mode, if a field is encountered without an equals sign (e.g., &key&), the parser raises a QuerystringParseError.
Sources: python_multipart/multipart.py:560-570, tests/test_multipart.py:382-390
Resource and Security Limits
The library implements several configuration-based limits to prevent Denial of Service (DoS) scenarios, which trigger specific exceptions when exceeded.
Configuration Limits Table
| Config Key | Associated Exception | Logic |
|---|---|---|
MAX_BODY_SIZE | N/A (Truncates) | The FormParser truncates data after this limit, preventing further processing. |
MAX_HEADER_COUNT | MultipartParseError | Raised if a single multipart part contains more headers than allowed (default 8). |
MAX_HEADER_SIZE | MultipartParseError | Raised if a header line exceeds the limit (default 4224 bytes). |
MAX_BOUNDARY_LENGTH | FormParserError | Raised during initialization if the boundary is longer than 256 bytes. |
Sources: python_multipart/multipart.py:105-115, python_multipart/multipart.py:721-730, python_multipart/multipart.py:1260-1270
File and I/O Errors
When files are flushed to disk due to MAX_MEMORY_FILE_SIZE being exceeded, the library interacts with the filesystem.
- File Creation: If
UPLOAD_DIRis specified but invalid, or if the system fails to create aNamedTemporaryFile, aFileErroris raised. - Write Failures: Errors during the
shutil.copyfileobjprocess or during direct writes to a file object are caught and re-raised asFileError.
# Example of FileError being raised during directory validation
try:
tmp_file = open(path, "w+b")
except OSError:
raise FileError("Error opening temporary file: %r" % path)
Sources: python_multipart/multipart.py:356-365, tests/test_multipart.py:150-160
Decoding Failures
The Base64Decoder and QuotedPrintableDecoder wrap the underlying writer and validate the encoding integrity.
- Base64 Alignment: The
Base64DecoderraisesDecodeErrorif the input is not a multiple of 4 bytes upon finalization or if invalid characters are encountered duringbinascii.a2b_base64conversion. - Content-Transfer-Encoding (CTE): The
FormParsercan be configured viaUPLOAD_ERROR_ON_BAD_CTEto raise aFormParserErrorif an unknown encoding is specified in the headers.
Sources: python_multipart/decoders.py:15-30, python_multipart/multipart.py:1240-1250, tests/test_multipart.py:1010-1025
Conclusion
The error handling system in python-multipart serves as both a protocol validator and a security layer. By leveraging a hierarchy of specialized exceptions and enforcing strict resource limits, the library ensures that consumers can safely handle untrusted streaming input while receiving actionable feedback via offsets and descriptive error messages.