---
title: "永久错误立即失败"
description: "当一次服务商调用可能以两种方式失败时，使用这个模式：一种是重试可能解决的暂时错误，另一种是任何重试都无法解决的永久错误。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/fail-fast-on-permanent-errors/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/failure-handling/fail-fast-on-permanent-errors.mdx"
locale: "zh-Hans"
language: "python"
---

> 供 AI Agent 使用的全部页面索引：https://docs.superdurable.io/zh-Hans/llms.txt

# 永久错误立即失败

本页代码为 Python。其他语言：[Go](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/fail-fast-on-permanent-errors.go.md) · [Java](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/fail-fast-on-permanent-errors.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/fail-fast-on-permanent-errors.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/fail-fast-on-permanent-errors.rust.md)

当一次服务商调用可能以两种方式失败时，使用这个模式：一种是重试可能解决的暂时错误，另一种是任何重试都无法解决的永久错误。

例如通过支付服务商支付一笔报销单。超时是暂时错误：下一次尝试可能成功。银行账户无效是永久错误：服务商已经拒绝了请求，每次重试都会得到同样的答复。

Step 重试会按 Step 的重试策略重试 Step 代码抛出的每一个错误。示例的重试调度预算是一小时，所以 `Execute` 抛出的永久错误会一直被重试，直到这个预算用完。改为在 `Execute` 中对错误分类，并立即转走永久错误。

**Flow 图：ExpenseReimbursementFlow**

**Step 列表**

1. `SubmitPayout`（起始 Step）：Submit the payout; retry a timeout and route a rejection at once. 下一步：`RecordRejectedClaim`，或 Flow 完成。 写入 `PayoutOutcome`。
2. `RecordRejectedClaim`：Record the rejected claim and its reason. 下一步：Flow 完成。 写入 `PayoutOutcome`。

例子: [examples/python/dex_examples/patterns/fail-fast/expense_reimbursement_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/fail-fast/expense_reimbursement_flow.py)

<a id="how-it-works"></a>

## 工作方式

- 对服务商的写操作放在 `Execute` 中。`Execute` 看到服务商的错误，并决定它的含义。`WaitFor` 中的只读调用遇到永久错误时，会把它交给 `Execute` 处理；见 [WaitFor 和 Execute](https://docs.superdurable.io/zh-Hans/concepts/step.md#waitfor-and-execute)。
- 让暂时错误使这次尝试失败：抛出或返回这个错误。Step 重试按 Step 自己的重试策略再次调用。
- 捕获永久错误，并返回一个 Step decision。转到一个失败处理 Step，由它记录业务失败。如果需要立即把整个 Flow 标记为失败，则改为返回 `ForceFail`。
- 只有服务商确认的错误才算永久错误，例如输入被拒绝或请求无效。未知错误仍按暂时错误处理，让重试继续覆盖它。
- 重试策略只按暂时错误来设定。已被转走的永久错误不会消耗它。
- 优先把可能失败的调用放在 `Execute` 中。`Execute` 在看到失败的同一次调用里，返回转走这个失败的 decision。
- 拒绝的 decision 提交后，这个错误不会再让 `SubmitPayout` 重试。失败处理 Step 是一个独立的 Step，Dex 仍可以单独重试它。
- 失败记录中只保存不敏感的信息。示例记录固定的原因，从不记录银行账号。

在示例中：

1. `ExpenseReimbursementFlow` 用报销单启动 `SubmitPayout`。Flow ID 就是报销单 ID，也是服务商的幂等键。
2. `SubmitPayout` 调用支付服务商。成功时，它把付款记录到 `PayoutOutcome` Attribute，并完成 Flow。
3. 服务商超时时，`SubmitPayout` 让这个错误使本次尝试失败。Step 重试带退避再次调用服务商，直到一小时的重试调度预算用完。
4. 服务商拒绝银行账户时，`SubmitPayout` 带着固定的原因转到 `RecordRejectedClaim`。这个错误不会让 `SubmitPayout` 重试。
5. `RecordRejectedClaim` 把拒绝记录到 `PayoutOutcome`，并完成 Flow。

<a id="example"></a>

## 示例

模拟服务商只接受由八位 ASCII 数字组成的银行账户，其他账户一律拒绝。每个有效报销单第一次提交时它会超时，之后才付款。可以在 [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground) 中运行 HTTP 示例。

**Python**

```python
class RecordRejectedClaim(Step[ClaimRejection]):
    def execute(self, context: Context, input: ClaimRejection) -> StepDecision:
        PAYOUT_OUTCOME.set(
            context, PayoutOutcome("REJECTED", input.reason, input.submit_attempt)
        )
        return graceful_complete(f"rejected: {input.reason}")


class SubmitPayout(Step[ExpenseClaim]):
    def __init__(self, provider: FakePaymentProvider) -> None:
        self.provider = provider

    def get_step_options(self) -> StepOptions:
        return StepOptions(
            execute_retry=RetryPolicy(
                initial_interval=timedelta(seconds=1),
                backoff_coefficient=2.0,
                maximum_interval=timedelta(minutes=5),
                total_duration=timedelta(hours=1),
            )
        )

    def execute(self, context: Context, input: ExpenseClaim) -> StepDecision:
        try:
            payout_id = self.provider.submit_payout(context.flow_id, input)
        except PayoutRejectedError as rejection:
            return go_to(
                RecordRejectedClaim, ClaimRejection(str(rejection), context.attempt)
            )
        PAYOUT_OUTCOME.set(context, PayoutOutcome("PAID", payout_id, context.attempt))
        return graceful_complete(payout_id)
```

例子: [examples/python/dex_examples/patterns/fail-fast/expense_reimbursement_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/fail-fast/expense_reimbursement_flow.py)

<a id="test-both-routes"></a>

## 测试两条路径

用 Step 真实的重试策略测试。缩短了重试策略的测试，测的已经不是这条路径。

- 让模拟服务商返回永久错误。断言 Flow 的终态，并断言结果来自 `SubmitPayout` 的第一次尝试。测试能观察到模拟服务商时，再断言它只被调用了一次。
- 让模拟服务商返回一次暂时错误。断言 Step 会重试，并在第二次尝试时成功。

示例从 `PayoutOutcome` Attribute 读取尝试次数，它记录了产生结果的那次尝试。

<a id="compared-with-execute-failure-recovery"></a>

## 与 Execute 失败恢复的区别

[Execute 失败恢复](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/execute-failure-recovery.md) 处理重试策略耗尽后仍然存在的失败。它的 `ExecuteFailure` 策略把 Flow 转到恢复 Step，恢复 Step 收到失败 Step 的输入。

永久错误立即失败在任何重试之前就做出决定。decision 由 `Execute` 自己返回，所以失败处理 Step 收到的是 `Execute` 构造的输入，例如拒绝原因。

一个 Step 两者都需要时，就一起使用：服务商确认的永久错误立即失败，同时为超出重试策略的暂时错误加上 `ExecuteFailure` 路径。

<a id="next"></a>

## 下一步

- [人工恢复](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/manual-recovery.md)
- [Retry and failure policies](https://docs.superdurable.io/zh-Hans/reference/python/failure-and-retries.md#retry-and-failure-policies)
- [失败处理](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling.md)
