TsgcWSCircuitBreakerMethods › Execute

Execute Method

Runs a protected action; checks IsCallAllowed first and records success / failure / slow automatically.

Overloads

Overload 1

Syntax

function Execute(const aKey: string; aAction: TProc): Boolean;

Parameters

NameTypeDescription
aKeyconst stringCircuit key the call belongs to — usually a hostname ('api.openai.com') or a logical service name. Each key owns its own state, counters and thresholds.
aActionTProcAnonymous procedure to run under the breaker. Any exception raised inside is classified and (if recorded) advances the failure counters before being re-raised to the caller.

Return Value

True if the action was executed (circuit Closed or HalfOpen trial allowed), False if it was rejected because the circuit was Open. When rejected the OnCallRejected event fires and, if Fallback is enabled, OnFallback fires next. (Boolean)

Remarks

The overload with explicit aKey evaluates IsCallAllowed(aKey) first. If allowed, it measures the action duration, calls RecordSuccess or RecordFailure according to the outcome (and RecordSlow when aDurationMs >= Thresholds.SlowCallDurationMs), then re-raises any exception to the caller. Requires Delphi 2009+ because it uses TProc. When the circuit is Open and Fallback.Enabled is True the OnFallback event fires so the caller can serve a cached payload; when Fallback is disabled the method returns False silently. Do not assume Execute suppresses exceptions: it still lets the caller see failures — the breaker only tracks them.

Example

// Run a protected call against OpenAI under key 'openai-api'
if not sgcWSCircuitBreaker1.Execute('openai-api',
  procedure
  begin
    CallOpenAIEndpoint;
  end) then
  LogRejected('Circuit open for openai-api');

Overload 2

Syntax

function Execute(aAction: TProc): Boolean;

Parameters

NameTypeDescription
aActionTProcAnonymous procedure to run under the breaker. Any exception raised inside is classified and (if recorded) advances the failure counters before being re-raised.

Return Value

True if the action ran, False if it was rejected because the circuit is Open. (Boolean)

Remarks

Shortcut for the two-argument overload that uses DefaultKey as the circuit key. Requires Delphi 2009+. Set DefaultKey to a meaningful name ('openai-api', 'payment-gateway') before calling so Metrics, OnStateChange and OnCallRejected report a readable label.

Example

sgcWSCircuitBreaker1.DefaultKey := 'openai-api';

// Single-key protected call — no need to pass the key each time
sgcWSCircuitBreaker1.Execute(
  procedure
  begin
    CallOpenAIEndpoint;
  end);

Back to Methods