# Try / Catch

> 定义错误处理的作用域。

Source: https://docs.sommatic.ai/zh/nodes/flow.try/

- 标识: `flow.try`
- 类别: 流程控制
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

定义错误处理的作用域。

该算子标记“Try”块的开始。连接到“do”端口的下游节点中发生的任何错误，都会被捕获并路由到对应的“Catch”处理器（在工作流图中按结构定义）。

**行为：**
- **正常流程：** 将载荷传递给“do”。
- **错误作用域：** 引擎将该节点注册为其子节点的错误处理器。
- **捕获：** 子节点中的错误会触发所配置的“Catch”算子（如有）。

**适用场景：**
- 包裹有风险的 API 调用。
- 为特定步骤实现“补偿事务”。
- 优雅降级（回退逻辑）。

## 配置

该节点没有配置项。

## 输出端口

- `do` (默认): Try 块的起点。

## 输入契约

- `payload` (object, 可选)

## 输出契约

- `payload` (object, 可选)

## 在表达式中

后续节点可通过 `$("Try / Catch").item.json.<路径>` 读取此节点输出中的内容（请把 `Try / Catch` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `do` 返回的路径，依据“端口”一节所示的输出。

- `$("Try / Catch").item.json.payload` (object) **worker 不返回：读取结果为 undefined.**
- `$("Try / Catch").item.json.order_id` (string) = `"ord_123"` (编辑器不提示)
- `$("Try / Catch").item.json.amount` (number) = `1250` (编辑器不提示)
- `$("Try / Catch").item.json.status` (string) = `"active"` (编辑器不提示)


## 工作原理

开启错误作用域：将原样的 payload 从 `do` 输出；其后任何节点抛出的异常都会被引擎发送到与其 `catch` 连线相接的节点。

1. 通过 `do` 返回解析后的 payload，并带 `meta.scope` `try_start`。
2. 引擎注册一个作用域，其 catch 节点为从本节点以 `from.port` `catch` 连出的第一个节点（也可能没有）。
3. 当后续节点抛出异常时，引擎从该节点反向遍历图；若本 try 节点是其祖先且有 catch 节点，引擎会将 catch 节点加入队列，而不是让运行失败。
4. catch 节点收到 `{ error, source_node, source_operator }`；失败节点的输出记录为 `{ error, stack }`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-try-sync",
  "label": "Try sync",
  "operator_slug": "flow.try",
  "operator_version": "1.0.0",
  "config": {}
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "order_id": "ord_123",
    "amount": 1250,
    "status": "active"
  },
  "port": "do",
  "meta": {
    "scope": "try_start"
  }
}
```

## 输出端口 (代码中的行为)

### `do`

始终触发：受保护分支的起点。

```json
{
  "order_id": "ord_123",
  "amount": 1250,
  "status": "active"
}
```

### `error`

仅当解析配置抛出异常时，实际中不会发生。

```json
{
  "error": "<message>"
}
```

## 说明与限制

- 只捕获抛出的异常。多数节点通过自身的 `error` 端口以信封形式报告失败（例如 `data.transform` 或 `flow.if`），这些会沿该端口流转，不会到达 catch 节点。会抛出的失败包括：无法解析的算子、无效的 `credential_bindings`，以及重新抛出错误的 worker（如 `sommatic.app.execute`）。
- `catch` 不是本节点声明的端口：引擎会查找 `from.port` 为 `catch` 的连线。没有这条连线时作用域仍会注册，但异常依旧会导致运行失败。
- 作用域持续到运行结束，覆盖所有以该 try 节点为祖先的节点，包括 catch 分支本身：catch 节点内抛出的异常会再次路由给它，直到 100 步上限导致运行失败。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "flow.try",
  "name": "Try / Catch",
  "category": "flow",
  "version": "1.0.0",
  "description": "Defines a scope for error handling.\n\n  This operator marks the beginning of a \"Try\" block. Any errors occurring in the downstream nodes connected to the 'do' port will be caught and routed to the corresponding \"Catch\" handler (structurally defined in the workflow graph).\n\n  **Behavior:**\n  - **Normal Flow:** Passes payload to 'do'.\n  - **Error Scoping:** The engine registers this node as the error handler for its children.\n  - **Catch:** Errors in children trigger the configured 'Catch' operator (if any).\n\n  **Use Cases:**\n  - Wrapping a risky API call.\n  - Implementing \"Compensating Transactions\" for a specific step.\n  - Graceful degradation (fallback logic).",
  "capabilities": [
    "error-handling",
    "scope",
    "try-catch"
  ],
  "config_schema": {
    "type": "object",
    "properties": {}
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "do",
      "label": "Do",
      "is_default": true,
      "description": "Start of the Try block."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "error",
    "try",
    "catch",
    "scope"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {}
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "do",
    "label": "Do",
    "is_default": true,
    "description": "Start of the Try block."
  }
]
```
