Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Langchain ai Langgraph SDK Errors

From Leeroopedia
Attribute Value
Source `libs/sdk-py/langgraph_sdk/errors.py` (231 lines)
Domain SDK, Error_Handling
Principle SDK_Error_Handling
Library sdk-py
Import `from langgraph_sdk.errors import APIError, NotFoundError, AuthenticationError`

Overview

The `errors.py` module in the `langgraph_sdk` package defines the complete error hierarchy for the LangGraph Python SDK. It provides a structured set of exception classes that map HTTP status codes to specific error types, along with helper functions for decoding error response bodies and mapping HTTP responses to the appropriate exception classes.

Description

The error hierarchy is built on two base classes:

`LangGraphError(Exception)` -- The root exception for all LangGraph SDK errors.

`APIError(httpx.HTTPStatusError, LangGraphError)` -- Base class for all API-related errors. Uses multiple inheritance from both `httpx.HTTPStatusError` (for compatibility with httpx error handling) and `LangGraphError`. Extracts `code`, `param`, and `type` fields from the response body when available.

Status-Specific Error Classes

`APIStatusError(APIError)` -- Base for HTTP status code errors. Adds `response`, `status_code`, and `request_id` attributes.

Class Status Code Description
`BadRequestError` 400 Malformed or invalid request.
`AuthenticationError` 401 Authentication failed or missing.
`PermissionDeniedError` 403 Authenticated but not authorized.
`NotFoundError` 404 Requested resource does not exist.
`ConflictError` 409 Resource conflict (e.g., concurrent modification).
`UnprocessableEntityError` 422 Request is well-formed but semantically invalid.
`RateLimitError` 429 Too many requests.
`InternalServerError` 500+ Server-side failure.

Connection Error Classes

`APIConnectionError(APIError)` -- Raised for network-level connection failures. Default message: `"Connection error."`.

`APITimeoutError(APIConnectionError)` -- Raised when a request times out. Message: `"Request timed out."`.

Validation Error

`APIResponseValidationError(APIError)` -- Raised when the response data does not match the expected schema. Message: `"Data returned by API invalid for expected schema."`.

Helper Functions

`_extract_error_message(body, fallback) -> str` -- Extracts a human-readable error message from a response body dict, looking for `"message"`, `"detail"`, or `"error"` keys (including nested `error.message`).

`_decode_error_body(r) -> object | None` / `_adecode_error_body(r) -> object | None` -- Sync and async functions that read the response body and attempt to decode it as JSON (via `orjson`), falling back to raw string decoding.

`_map_status_error(response, body) -> APIStatusError` -- Maps an HTTP response to the appropriate `APIStatusError` subclass based on the status code.

`_raise_for_status_typed(r)` / `_araise_for_status_typed(r)` -- Sync and async functions that check the response status and raise the appropriate typed error if the status code is 400 or above. Logs the error for Python versions prior to 3.11 (which lack Exception notes).

Usage

from langgraph_sdk.errors import APIError, NotFoundError, AuthenticationError

try:
    result = await client.threads.get("nonexistent-id")
except NotFoundError as e:
    print(f"Thread not found: {e.message}")
except AuthenticationError as e:
    print(f"Auth failed: {e.message}")
except APIError as e:
    print(f"API error {e.status_code}: {e.message}")

Code Reference

Error Class Hierarchy

Exception
  LangGraphError
    APIError (also inherits httpx.HTTPStatusError)
      APIResponseValidationError
      APIStatusError
        BadRequestError (400)
        AuthenticationError (401)
        PermissionDeniedError (403)
        NotFoundError (404)
        ConflictError (409)
        UnprocessableEntityError (422)
        RateLimitError (429)
        InternalServerError (500+)
      APIConnectionError
        APITimeoutError

APIError Attributes

Attribute Type Description
`message` `str` Human-readable error message.
`request` `httpx.Request` The original HTTP request.
`body` None` Decoded response body (dict, string, or None).
`code` None` Machine-readable error code from body, if present.
`param` None` Parameter that caused the error, if present.
`type` None` Error type classification, if present.

APIStatusError Additional Attributes

Attribute Type Description
`response` `httpx.Response` The HTTP response object.
`status_code` `int` The HTTP status code.
`request_id` None` Value of the `x-request-id` response header, if present.

Helper Functions

Function Signature Description
`_extract_error_message` `(body, fallback) -> str` Extract error message from response body dict.
`_decode_error_body` None` Sync: read and decode response body.
`_adecode_error_body` None` Async: read and decode response body.
`_map_status_error` `(response, body) -> APIStatusError` Map HTTP response to appropriate error class.
`_raise_for_status_typed` `(r: httpx.Response) -> None` Sync: raise typed error if status >= 400.
`_araise_for_status_typed` `async (r: httpx.Response) -> None` Async: raise typed error if status >= 400.

I/O Contract

Aspect Detail
Input HTTP responses from the LangGraph API server (via `httpx`).
Output Typed exception instances with structured error information.
Side Effects Errors are logged for Python < 3.11 (using `logging.error`).
Dependencies `httpx` for HTTP types, `orjson` for JSON decoding.

Usage Examples

Catching Specific Errors

from langgraph_sdk.errors import (
    NotFoundError,
    AuthenticationError,
    RateLimitError,
    APIConnectionError,
)

async def safe_get_thread(client, thread_id):
    try:
        return await client.threads.get(thread_id)
    except NotFoundError:
        return None
    except AuthenticationError:
        raise RuntimeError("Invalid API credentials")
    except RateLimitError as e:
        print(f"Rate limited. Request ID: {e.request_id}")
        raise
    except APIConnectionError:
        print("Could not connect to LangGraph server")
        raise

Handling All API Errors

from langgraph_sdk.errors import APIError

async def run_with_error_handling(client, thread_id, input_data):
    try:
        return await client.runs.create(thread_id, input=input_data)
    except APIError as e:
        print(f"API Error [{e.status_code}]: {e.message}")
        if e.body:
            print(f"Response body: {e.body}")
        raise

Accessing Error Metadata

from langgraph_sdk.errors import APIStatusError

try:
    result = await client.threads.create()
except APIStatusError as e:
    print(f"Status: {e.status_code}")
    print(f"Message: {e.message}")
    print(f"Request ID: {e.request_id}")
    print(f"Error code: {e.code}")
    print(f"Error type: {e.type}")

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment