JSON Encode Error

Purpose

The **JSON Encode Error** addresses the need for a distinct and clear exception type that signals failures during JSON serialization in the library. Unlike generic Python exceptions, this custom error subclassing from [TypeError](/projects/287/67737) specifically categorizes encoding issues, enabling client code to catch and handle serialization errors distinctly from other exceptions.

This error type helps identify problems such as unsupported Python object types, failures in custom fallback serialization handlers, or violations of serialization options (e.g., attempting to serialize non-string dictionary keys without enabling the appropriate option). By defining this specific exception, the library improves error clarity, debuggability, and integration robustness.

Functionality

The `JSONEncodeError` functions as the exception raised internally when the serialization process encounters an object or condition it cannot convert to JSON bytes. Its key characteristics include:

An example minimal snippet illustrating its usage in Python bindings:

from orjson import JSONEncodeError, dumps

try:
    # Attempt to serialize a Python object not supported natively
    dumps(object())
except JSONEncodeError as err:
    print(f"Serialization failed: {err}")

Internally, the Rust serialization code signals errors by creating and returning this exception type to Python through PyO3 bindings, ensuring consistent error handling across language boundaries.

Integration

`JSONEncodeError` integrates tightly within the serialization subsystem and complements other error handling strategies:

Unlike the parent topic’s general discussion on error types, this subtopic focuses solely on the serialization side, providing a dedicated exception class for encoding faults. This specialization allows serialization workflows, benchmarking scripts, and API consumers to distinctly manage encoding errors without conflating them with parsing or runtime errors.

Diagram

sequenceDiagram
    participant PythonCaller as Python Caller
    participant PyO3 as PyO3 FFI Layer
    participant RustSerializer as Rust Serialization Core

    PythonCaller->>PyO3: calls dumps(obj)
    PyO3->>RustSerializer: serialize obj
    alt Serialization successful
        RustSerializer-->>PyO3: JSON bytes
        PyO3-->>PythonCaller: returns bytes
    else Serialization error
        RustSerializer-->>PyO3: create JSONEncodeError with message
        PyO3-->>PythonCaller: raises JSONEncodeError
    end

This sequence diagram shows the flow during serialization, highlighting the point where `JSONEncodeError` is generated and propagated back to the Python caller when serialization fails.


The `JSONEncodeError` serves as the focused mechanism to report and handle JSON serialization errors, providing clarity and control within the broader error management framework of the library.