共用方式為


在 Durable Functions (Azure Functions) 中處理錯誤

Durable Function 協調流程會在程式碼中實作,且可以使用程式設計語言的內建錯誤處理功能。 將錯誤處理和補償新增至協調流程時,確實已沒有任何新的概念需要了解。 不過,有一些行為值得注意。

附註

適用於 Azure Functions 的第 4 版 Node.js 程式設計模型已正式推出。 新的 v4 模型旨在為 JavaScript 和 TypeScript 開發人員提供更靈活的直覺式體驗。 如需深入了解 v3 與 v4 之間的差異,請參閱移轉指南

在下列程式碼片段中,JavaScript (PM4) 表示程式設計模型 V4,這是新的體驗。

活動函式和子編排中的錯誤

在 Durable Functions 中,活動函式或子協調流程內擲回的未處理例外狀況會使用標準化的例外狀況類型被傳回給處理回協調器函式。

例如,請考慮下列協調器函式,可在兩個帳戶之間執行資金轉移:

在 Durable Functions C# 同進程中,未處理例外會以 FunctionFailedException 的形式拋出。

例外狀況訊息通常會識別哪些活動函式或子協調流程導致失敗。 若要存取更詳細的錯誤資訊,請檢查 InnerException 屬性。

[FunctionName("TransferFunds")]
public static async Task Run([OrchestrationTrigger] IDurableOrchestrationContext context)
{
    var transferDetails = context.GetInput<TransferOperation>();

    await context.CallActivityAsync("DebitAccount",
        new
        {
            Account = transferDetails.SourceAccount,
            Amount = transferDetails.Amount
        });

    try
    {
        await context.CallActivityAsync("CreditAccount",
            new
            {
                Account = transferDetails.DestinationAccount,
                Amount = transferDetails.Amount
            });
    }
    catch (FunctionFailedException)
    {
        // Refund the source account.
        // Another try/catch could be used here based on the needs of the application.
        await context.CallActivityAsync("CreditAccount",
            new
            {
                Account = transferDetails.SourceAccount,
                Amount = transferDetails.Amount
            });
    }
}

附註

先前的 C# 範例適用於 Durable Functions 2.x。 針對 Durable Functions 1.x,您必須使用 DurableOrchestrationContext 而不是 IDurableOrchestrationContext。 如需版本差異的詳細資訊,請參閱 Durable Functions 版本一文。

如果首次 CreditAccount 函式呼叫失敗,協調器函式會將款項匯回到來源帳戶,以進行彌補。

實體函式中的錯誤

實體函式的例外狀況處理行為會根據 Durable Functions 裝載模型而有所不同:

在使用 C# 同處理序的 Durable Functions 中,實體函式擲回的原始例外狀況類型會被直接傳回至協調器。

[FunctionName("Function1")]
public static async Task<string> RunOrchestrator(
    [OrchestrationTrigger] IDurableOrchestrationContext context)
{
    try
    {
        var entityId = new EntityId(nameof(Counter), "myCounter");
        await context.CallEntityAsync(entityId, "Add", 1);
    }
    catch (Exception ex)
    {
        // The exception type will be InvalidOperationException with the message "this is an entity exception".
    }
    return string.Empty;
}

[FunctionName("Counter")]
public static void Counter([EntityTrigger] IDurableEntityContext ctx)
{
    switch (ctx.OperationName.ToLowerInvariant())
    {
        case "add":
            throw new InvalidOperationException("this is an entity exception");
        case "get":
            ctx.Return(ctx.GetState<int>());
            break;
    }
}

失敗時自動重試

當您呼叫活動函式或子協調流程函式時,您可以指定自動重試原則。 下列範例會嘗試呼叫函式最多 3 次,並於每次重試之間等待 5 秒鐘:

[FunctionName("TimerOrchestratorWithRetry")]
public static async Task Run([OrchestrationTrigger] IDurableOrchestrationContext context)
{
    var retryOptions = new RetryOptions(
        firstRetryInterval: TimeSpan.FromSeconds(5),
        maxNumberOfAttempts: 3);

    await context.CallActivityWithRetryAsync("FlakyFunction", retryOptions, null);

    // ...
}

附註

先前的 C# 範例適用於 Durable Functions 2.x。 針對 Durable Functions 1.x,您必須使用 DurableOrchestrationContext 而不是 IDurableOrchestrationContext。 如需版本差異的詳細資訊,請參閱 Durable Functions 版本一文。

上一個範例中的活動函式呼叫會採用設定自動重試原則的參數。 自訂自動重試原則有幾個選項:

  • 嘗試次數上限:嘗試次數上限。 如果設定為 1,則不會進行重試。
  • 第一次重試間隔:第一次重試嘗試之前等候的時間量。
  • 輪詢係數:用來決定輪詢增加速率的係數。 預設值為 1。
  • 最大重試間隔:重試嘗試之間等候的最大時間量。
  • 重試逾時:花費在重試的最大時間量。 預設行為是無限期地重試。

自訂重試處理常式

使用 .NET 或 JAVA 時,您也可以選擇在程式碼中實作重試處理常式。 當宣告式重試策略不夠表達力時,這會很有用。 對於未支援自訂重試處理常式的語言,您仍然可以選擇使用迴圈、例外狀況處理及計時器來實作重試原則,以插入重試之間的延遲。

RetryOptions retryOptions = new RetryOptions(
    firstRetryInterval: TimeSpan.FromSeconds(5),
    maxNumberOfAttempts: int.MaxValue)
    {
        Handle = exception =>
        {
            // True to handle and try again, false to not handle and throw.
            if (exception is TaskFailedException failure)
            {
                // Exceptions from TaskActivities are always this type. Inspect the
                // inner Exception to get more details.
            }

            return false;
        };
    }

await ctx.CallActivityWithRetryAsync("FlakeyActivity", retryOptions, null);

函式逾時

如果協調器函式內的函式呼叫太久才完成,您可以放棄此函式呼叫。 目前,適當的作法是使用 "any" 工作選取器來建立永久性計時器,如下列範例所示:

[FunctionName("TimerOrchestrator")]
public static async Task<bool> Run([OrchestrationTrigger] IDurableOrchestrationContext context)
{
    TimeSpan timeout = TimeSpan.FromSeconds(30);
    DateTime deadline = context.CurrentUtcDateTime.Add(timeout);

    using (var cts = new CancellationTokenSource())
    {
        Task activityTask = context.CallActivityAsync("FlakyFunction");
        Task timeoutTask = context.CreateTimer(deadline, cts.Token);

        Task winner = await Task.WhenAny(activityTask, timeoutTask);
        if (winner == activityTask)
        {
            // success case
            cts.Cancel();
            return true;
        }
        else
        {
            // timeout case
            return false;
        }
    }
}

附註

先前的 C# 範例適用於 Durable Functions 2.x。 針對 Durable Functions 1.x,您必須使用 DurableOrchestrationContext 而不是 IDurableOrchestrationContext。 如需版本差異的詳細資訊,請參閱 Durable Functions 版本一文。

附註

此機制實際上不會終止進行中的活動函式執行。 只是讓協調器函式略過結果並繼續執行。 如需詳細資訊,請參閱計時器文件。

未處理的例外狀況

如果協調器函式失敗並傳回未處理的例外狀況,例外狀況的詳細資料會記錄下來,而在執行個體會以 Failed 狀態結束。

為 FailureDetails 包含自訂例外狀況屬性 (在 .NET 隔離模式下)

在 .NET 隔離模型中執行持久性工作工作流程時,工作失敗會自動序列化為 FailureDetails 物件。 依預設,此物件包含標準欄位,例如:

  • ErrorType — 例外狀況類型名稱
  • 訊息 — 例外狀況訊息
  • StackTrace — 序列化堆疊追蹤
  • InnerFailure – 用於遞迴內部例外狀況的巢狀 FailureDetails 物件

從 Microsoft.Azure.Functions.Worker.Extensions.DurableTask v1.9.0 開始,您可以實作 IExceptionPropertiesProvider (從 v1.16.1套件開始定義在 Microsoft.DurableTask.Worker 中) 來擴充此行為。 此提供者會定義哪些例外狀況類型,以及哪些屬性應該包含在 FailureDetails.Properties 字典中。

附註

  • 此功能僅適用於 .NET Isolated 。 未來版本將新增對 Java 的支援。
  • 請確定您使用的是 Microsoft.Azure.Functions.Worker.Extensions.DurableTask v1.9.0 或更新版本。
  • 請確定您使用的是 Microsoft.DurableTask.Worker v1.16.1 或更新版本。

實作例外狀況屬性提供者

實作自訂 IExceptionPropertiesProvider,以擷取並傳回您關心的例外狀況的選取屬性。 當擲回相符的例外狀況類型時,傳回的字典將會被序列化到 FailureDetails 的 Properties 欄位中。

using Microsoft.DurableTask.Worker;

public class CustomExceptionPropertiesProvider : IExceptionPropertiesProvider
{
    public IDictionary<string, object?>? GetExceptionProperties(Exception exception)
    {
        return exception switch
        {
            ArgumentOutOfRangeException e => new Dictionary<string, object?>
            {
                ["ParamName"] = e.ParamName,
                ["ActualValue"] = e.ActualValue
            },
            InvalidOperationException e => new Dictionary<string, object?>
            {
                ["CustomHint"] = "Invalid operation occurred",
                ["TimestampUtc"] = DateTime.UtcNow
            },
            _ => null // Other exception types not handled
        };
    }
}

註冊提供者

在 .NET 隔離背景工作主機中註冊自訂 IExceptionPropertiesProvider,通常是在 Program.cs 中進行:

using Microsoft.DurableTask.Worker;
using Microsoft.Extensions.DependencyInjection;

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults(builder =>
    {
        // Register custom exception properties provider
        builder.Services.AddSingleton<IExceptionPropertiesProvider, CustomExceptionPropertiesProvider>();
    })
    .Build();

host.Run();

註冊之後,任何符合其中一個已處理類型之例外狀況,都會自動在其 FailureDetails 中包含已設定的屬性。

範例 FailureDetails 輸出

當發生符合提供者設定的例外狀況時,協調流程會收到序列化的 FailureDetails 結構,如下所示:

{
  "errorType": "TaskFailedException",
  "message": "Activity failed with an exception.",
  "stackTrace": "...",
  "innerFailure": {
    "errorType": "ArgumentOutOfRangeException",
    "message": "Specified argument was out of range.",
    "properties": {
      "ParamName": "count",
      "ActualValue": 42
    }
  }
}

後續步驟