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 Auth HTTPException

From Leeroopedia
Attribute Value
Source `libs/sdk-py/langgraph_sdk/auth/exceptions.py` (59 lines)
Domain Authentication, Error_Handling
Principle Server_Authentication
Library sdk-py
Import `from langgraph_sdk.auth.exceptions import HTTPException`

Overview

The `exceptions.py` module in the `langgraph_sdk.auth` package defines the `HTTPException` class, an exception type for returning specific HTTP error responses from the authentication layer of LangGraph Server. Since it resides in the auth module, it defaults to a 401 "Unauthorized" status code.

Description

`HTTPException(Exception)` is a lightweight exception class designed to be raised within authentication handlers to signal HTTP errors. When raised, it is caught by the server framework and translated into the corresponding HTTP response.

Key characteristics:

  • Default status code: 401 -- Since this exception lives in the auth module, the default assumes an authentication failure.
  • Automatic detail from status code -- If no `detail` string is provided, the class uses Python's `http.HTTPStatus` to derive a human-readable phrase (e.g., `"Unauthorized"`, `"Not Found"`, `"Forbidden"`).
  • Optional headers -- Supports additional HTTP headers (e.g., `WWW-Authenticate: Bearer`) that will be included in the error response.
  • Clean string representations -- `__str__` returns `"{status_code}: {detail}"` and `__repr__` returns `"HTTPException(status_code={code!r}, detail={detail!r})"`.

Attributes

  • `status_code: int` -- The HTTP status code (default 401).
  • `detail: str` -- The error detail message.
  • `headers: Mapping[str, str] | None` -- Optional additional response headers.

Usage

from langgraph_sdk.auth.exceptions import HTTPException

# Raise with defaults (401 Unauthorized)
raise HTTPException()

# Raise with custom status and detail
raise HTTPException(status_code=403, detail="Insufficient permissions")

# Raise with additional headers
raise HTTPException(headers={"WWW-Authenticate": "Bearer"})

Code Reference

HTTPException Class

Method Signature Description
`__init__` `(status_code=401, detail=None, headers=None)` Initialize the exception with status, detail, and optional headers.
`__str__` `() -> str` Returns `"{status_code}: {detail}"`.
`__repr__` `() -> str` Returns `"HTTPException(status_code={code!r}, detail={detail!r})"`.

Constructor Parameters

Parameter Type Default Description
`status_code` `int` `401` HTTP status code for the error response.
`detail` None` `None` Detailed error message. Uses `http.HTTPStatus` phrase if `None`.
`headers` None` `None` Additional HTTP headers to include in the error response.

Instance Attributes

Attribute Type Description
`status_code` `int` The HTTP status code.
`detail` `str` The error detail message (never `None` after initialization).
`headers` None` Optional response headers.

I/O Contract

Aspect Detail
Input Optional status code, detail message, and headers at construction time.
Output When raised and caught by the server, produces an HTTP error response with the specified status code, detail, and headers.
Side Effects None directly. The server framework catches this exception and converts it to an HTTP response.
Default Behavior Without arguments, produces a `401 Unauthorized` response.

Usage Examples

Default Authentication Error

from langgraph_sdk.auth.exceptions import HTTPException

async def authenticate(request):
    token = request.headers.get("Authorization")
    if not token:
        raise HTTPException()
        # Results in: 401 Unauthorized

Custom Error with Headers

from langgraph_sdk.auth.exceptions import HTTPException

async def authenticate(request):
    token = request.headers.get("Authorization")
    if not token:
        raise HTTPException(
            status_code=401,
            detail="Bearer token required",
            headers={"WWW-Authenticate": "Bearer"},
        )

Not Found Error

from langgraph_sdk.auth.exceptions import HTTPException

async def get_resource(resource_id: str):
    resource = await db.find(resource_id)
    if resource is None:
        raise HTTPException(status_code=404, detail="Resource not found")
    return resource

Permission Denied Error

from langgraph_sdk.auth.exceptions import HTTPException

async def authorize(user, action):
    if action not in user.permissions:
        raise HTTPException(
            status_code=403,
            detail=f"User lacks permission for '{action}'",
        )

Related Pages

Page Connections

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