处理langgraph中node发生error

如果langgraph中某个节点报错了,该如何try except

可以,最常见的做法就是:try/except 写在节点函数内部
因为 LangGraph 的节点本质上就是一个接收 state、返回 state 更新的 Python 函数,所以你完全可以像普通函数一样(LangChain 文档)M/流程可恢复错误写进 state 继续流转,需要用户补信息时用 interrupt()未知错误**直接抛出方便排查。(LangChain 文档)

from typing_extensions import TypedDict

class State(TypedDict, total=False):
    query: str
    result: str
    error: str

def my_node(state: State):
    try:
        result = do_something(state["query"])
        return {
            "result": result,
            "error": ""
        }
    except ValueError as e:
        # 可预期业务错误:写回 state,不让整个 graph 崩掉
        return {
            "error": f"参数不合法: {e}"
        }

如果你不只是想“记录错误”,而是想报错后跳到别的节点,更适合用 Command

from typing_extensions import TypedDict, Literal
from langgraph.types import Command

class State(TypedDict, total=False):
    query: str
    result: str
    error: str

def risky_node(state: State) -> Command[Literal["next_node", "fallback_node"]]:
    try:
        result = do_something(state["query"])
        return Command(
            update={"result": result, "error": ""},
            goto="next_node"
        )
    except Exception as e:
        return Command(
            update={"error": str(e)},
            goto="fallback_node"
        )

这类“把错误写进 state,再回到 agent/下一个补救节点继续跑”的模式,正是官方文档给的推荐示例。(LangChain 文档)网络抖动、限流、临时 5xx 这种“重试一下可能就好”的错误,官方更推荐不要手写一层层 try/except + sleep,而是给节点加 retry_policy:(LangChain 文档)n
from langgraph.graph import StateGraph
from langgraph.types import RetryPolicy

builder = StateGraph(State)

builder.add_node(
"my_node",
my_node,
retry_policy=RetryPolicy(max_attempts=3, initial_interval=1.0)
)


官方文档说明,`retry_policy` 是在 `add_node(..., retry_policy=...)` 上配的;默认 `retry_on` 会重试很多异常,但**不会**重试像 `ValueError`、`TypeError`、`RuntimeError`、`OSError` 这类异常;对 `requests` / `httpx` 这类 HTTP 库,默认只重试 **5xx**。:contentReference[oaicite:8]{index=8}一点,比如:  
**第一次失败走主服务,第二次失败改走备用服务**,可以在节点里读 `runtime.execution_info.node_attempt`。这个能力官方文档注明 **`langgraph>=1.1.3`** 可用。:contentReference[oaicite:10]{index=10}n
from langgraph.runtime import Runtime

def my_node(state: State, runtime: Runtime):
    info = runtime.execution_info

    try:
        if info.node_attempt > 1:
            return {"result": call_fallback_api()}
        return {"result": call_primary_api()}
    except Exception as e:
        return {"error": str(e)}

实战里我建议你这样分:

  1. 业务可预期错误:节点内 try/except,写入 state["error"]
  2. 临时性错误:配 retry_policy
  3. 需要人工补信息interrupt()
  4. 真正不该发生的 bug:不要吞,直接抛出

一个比较稳的模板是:

def node(state: State):
    try:
        data = call_api_or_tool(state)
        return {"result": data, "error": ""}
    except KnownBusinessError as e:
        # 可恢复:继续图流程
        return {"error": f"业务错误: {e}"}
    except Exception:
        # 未知错误:直接抛,让 LangSmith / 日志看得到
        raise

你这个问题的核心答案就是:LangGraph 没有单独的“节点级 try/except 语法”,就是在节点函数里按普通 Python 写;但“临时错误”最好交给 retry_policy,不要全部自己吞掉。 这是官方当前推荐方式。(LangChain 文档)代码贴出来,我可以直接按你的 graph 结构给你改成可用版本。

posted @ 2026-04-14 11:22  X1OO  阅读(5)  评论(0)    收藏  举报