Agent Action Error Handling
Agentforce agents receive the return value of an Invocable action as-is and feed it back into the LLM loop. An unhandled exception becomes a Flow or framework error — the agent cannot reason about it, often re-invokes the action with the same inputs, and occasionally confabulates success. This skill defines a Response type that always returns (status, reason_code, user_message) so the subagent instructions can route deterministically.
Terminology. Salesforce renamed agent topics to subagents in April 2026.
Nothing about behaviour changed, and the API surface kept the old word —
GenAiPlugin is still the metadata type behind a subagent, and GenAiFunction
is still the action. This skill says subagent instructions for what older
docs and your org's metadata call topic instructions.
The Platform Rule Everything Follows From
An @InvocableMethod must return one result per input, in the same order,
even when errors occur — the inputs and outputs "must match on both the size
and the order"
(InvocableMethod Annotation).
So an error is not an exception you throw. It is a value you return in the
slot belonging to the failing request. A thrown exception breaks the contract
for the whole batch, not just the request that failed.
Two further platform rules shape the class: the method must be static,
public or global, and live in an outer class; and there is one
invocable method per class. One action is one verb — see
templates/agentforce/AgentActionSkeleton.cls.
The Envelope
| Field |
Type |
Purpose |
status |
OK | USER_ERROR | SYSTEM_ERROR |
Locus of control — whose problem is this |
reasonCode |
stable enum string |
What the subagent instructions branch on |
userMessage |
≤140 chars, authored |
Safe to read aloud verbatim |
retryable |
Boolean |
Would the same inputs plausibly succeed |
status and retryable are independent axes. A row lock is a retryable system
error; a validation failure is a terminal user error; a 503 is a retryable
system error. Collapsing them into one Boolean success is the single most
common cause of agent retry loops.
Recommended Workflow
- Design the Response class with the four fields above. Register every
reasonCode in Agent_Reason_Code__mdt so Apex, subagent instructions, and
dashboards share one contract.
- Structure the method in two phases — validate and collect, then one bulkified
Database.<dml>(records, false, AccessLevel.USER_MODE) — and assign results
back by index into a pre-sized output list. Per-row DML raises an
uncatchable LimitException under bulk invocation, which defeats every
catch you write.
- Classify by locus of control, branching on
Database.Error.getStatusCode()
or the HTTP status code — never on message text, which is localised and
reworded between releases. Log the raw exception to
templates/apex/ApplicationLogger.cls; never put getMessage() in
userMessage.
- Write one test per reason code asserting the code, the
retryable flag, and
that no raw platform error text reached userMessage. Coverage percentage is
not the signal; assertions-per-reason-code is.
- Add one subagent instruction per outcome class, including an explicit "do not
call the action again" for terminal codes — the planner's default on an
unsatisfied goal is to retry.
- Run the Testing Center /
sf agent test run scenarios that exercise each
branch and confirm the agent's wording matches the instruction for each code.
Key Considerations
userMessage is user-visible and lands in a stored transcript. Validation-rule
error text can interpolate field values, so getMessage() is a PII channel as
well as an implementation-detail leak.
- Distinguishing
NOT_FOUND from NO_ACCESS helps internal users and leaks
record existence on a guest channel. Decide per channel.
retryable = true on a mutating action requires idempotency (a caller-supplied
key upserted on an External Id). Otherwise a retried timeout is a duplicate
write.
- The
@InvocableMethod and @InvocableVariable description values are read
by the planner to decide whether to call the action, and pre-fill the
instruction fields in Agentforce Builder — they are functional, not
documentation.
- Watch the
SYSTEM_ERROR/UNKNOWN ratio in production. It is the direct
measure of classification debt; a jump after a release means an upstream
contract changed.
Worked Examples (see references/examples.md)
- Typed Response envelope for a Case-update action — Agentforce service agent closes Cases on user request.
- Stable reason_code enum across releases — A new DML error type appears after a managed-package install.
Common Gotchas (see references/gotchas.md)
- Throwing AuraHandledException from an Invocable — The agent receives an opaque framework message and loops.
- Governor-limit exceptions pre-empt your catch — LimitException (uncatchable) kills the transaction — agent sees raw Flow failure.
- Empty list returned when input list is empty — Agent receives an empty array and hallucinates a success message.
Top LLM Anti-Patterns (full list in references/llm-anti-patterns.md)
- Rethrowing exceptions from an @InvocableMethod — the LLM cannot reason about framework errors.
- Putting
ex.getMessage() directly into user_message — leaks internals and breaks deterministic subagent routing.
- Using boolean
success instead of a reason_code enum — the agent cannot distinguish retryable from terminal failures.
Official Sources Used
1---2name: agent-action-error-handling3description: "Design Invocable Apex actions that return deterministic, agent-friendly errors instead of surfacing raw exceptions to the LLM. NOT for authoring the action itself — @InvocableMethod schema, labels, security context — use agentforce/custom-agent-actions-apex. NOT for the Apex tests that force each error branch — use agentforce/agent-action-unit-tests."4category: agentforce5salesforce-version: "Spring '25+"6well-architected-pillars:7 - Reliability8 - Security9triggers:10 - "my agent action throws and the agent loops"11 - "invocable action leaks stack trace to user"12 - "how should I classify errors for an agent"13 - "agent retries after a validation rule failure"14tags:15 - agentforce16 - invocable-actions17 - error-handling18 - apex19inputs:20 - "Invocable action Apex class"21 - "expected agent behavior on failure"22outputs:23 - "Updated class returning typed error envelope"24 - "topic instruction update for retry vs. terminal errors"25dependencies: []26version: 1.0.127author: Pranav Nagrecha28updated: 2026-08-1429metadata:30 source: https://skillmd.com/skills/pranavnagrecha/agent-action-error-handling31---3233# Agent Action Error Handling3435Agentforce agents receive the return value of an Invocable action as-is and feed it back into the LLM loop. An unhandled exception becomes a Flow or framework error — the agent cannot reason about it, often re-invokes the action with the same inputs, and occasionally confabulates success. This skill defines a Response type that always returns (status, reason_code, user_message) so the subagent instructions can route deterministically.3637> **Terminology.** Salesforce renamed agent *topics* to *subagents* in April 2026.38> Nothing about behaviour changed, and the API surface kept the old word —39> `GenAiPlugin` is still the metadata type behind a subagent, and `GenAiFunction`40> is still the action. This skill says *subagent instructions* for what older41> docs and your org's metadata call *topic instructions*.4243## The Platform Rule Everything Follows From4445An `@InvocableMethod` must return one result per input, **in the same order,46even when errors occur** — the inputs and outputs *"must match on both the size47and the order"*48([InvocableMethod Annotation](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_InvocableMethod.htm)).4950So an error is not an exception you throw. It is a **value you return in the51slot belonging to the failing request**. A thrown exception breaks the contract52for the whole batch, not just the request that failed.5354Two further platform rules shape the class: the method must be `static`,55`public` or `global`, and live in an **outer** class; and there is **one56invocable method per class**. One action is one verb — see57`templates/agentforce/AgentActionSkeleton.cls`.5859## The Envelope6061| Field | Type | Purpose |62|---|---|---|63| `status` | `OK` \| `USER_ERROR` \| `SYSTEM_ERROR` | Locus of control — whose problem is this |64| `reasonCode` | stable enum string | What the subagent instructions branch on |65| `userMessage` | ≤140 chars, authored | Safe to read aloud verbatim |66| `retryable` | Boolean | Would the *same* inputs plausibly succeed |6768`status` and `retryable` are independent axes. A row lock is a retryable system69error; a validation failure is a terminal user error; a 503 is a retryable70system error. Collapsing them into one `Boolean success` is the single most71common cause of agent retry loops.7273## Recommended Workflow74751. Design the Response class with the four fields above. Register every76 `reasonCode` in `Agent_Reason_Code__mdt` so Apex, subagent instructions, and77 dashboards share one contract.782. Structure the method in two phases — validate and collect, then one bulkified79 `Database.<dml>(records, false, AccessLevel.USER_MODE)` — and assign results80 back by index into a pre-sized output list. Per-row DML raises an81 *uncatchable* `LimitException` under bulk invocation, which defeats every82 `catch` you write.833. Classify by locus of control, branching on `Database.Error.getStatusCode()`84 or the HTTP status code — never on message text, which is localised and85 reworded between releases. Log the raw exception to86 `templates/apex/ApplicationLogger.cls`; never put `getMessage()` in87 `userMessage`.884. Write one test per reason code asserting the code, the `retryable` flag, and89 that no raw platform error text reached `userMessage`. Coverage percentage is90 not the signal; assertions-per-reason-code is.915. Add one subagent instruction per outcome class, including an explicit *"do not92 call the action again"* for terminal codes — the planner's default on an93 unsatisfied goal is to retry.946. Run the Testing Center / `sf agent test run` scenarios that exercise each95 branch and confirm the agent's wording matches the instruction for each code.9697## Key Considerations9899- `userMessage` is user-visible and lands in a stored transcript. Validation-rule100 error text can interpolate field values, so `getMessage()` is a PII channel as101 well as an implementation-detail leak.102- Distinguishing `NOT_FOUND` from `NO_ACCESS` helps internal users and leaks103 record existence on a guest channel. Decide per channel.104- `retryable = true` on a mutating action requires idempotency (a caller-supplied105 key upserted on an External Id). Otherwise a retried timeout is a duplicate106 write.107- The `@InvocableMethod` and `@InvocableVariable` `description` values are read108 by the planner to decide whether to call the action, and pre-fill the109 instruction fields in Agentforce Builder — they are functional, not110 documentation.111- Watch the `SYSTEM_ERROR/UNKNOWN` **ratio** in production. It is the direct112 measure of classification debt; a jump after a release means an upstream113 contract changed.114115## Worked Examples (see `references/examples.md`)116117- *Typed Response envelope for a Case-update action* — Agentforce service agent closes Cases on user request.118- *Stable reason_code enum across releases* — A new DML error type appears after a managed-package install.119120## Common Gotchas (see `references/gotchas.md`)121122- **Throwing AuraHandledException from an Invocable** — The agent receives an opaque framework message and loops.123- **Governor-limit exceptions pre-empt your catch** — LimitException (uncatchable) kills the transaction — agent sees raw Flow failure.124- **Empty list returned when input list is empty** — Agent receives an empty array and hallucinates a success message.125126## Top LLM Anti-Patterns (full list in `references/llm-anti-patterns.md`)127128- Rethrowing exceptions from an @InvocableMethod — the LLM cannot reason about framework errors.129- Putting `ex.getMessage()` directly into user_message — leaks internals and breaks deterministic subagent routing.130- Using boolean `success` instead of a reason_code enum — the agent cannot distinguish retryable from terminal failures.131132## Official Sources Used133134- InvocableMethod Annotation (Apex Developer Guide) — https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_InvocableMethod.htm135- Create Custom Actions Using Apex InvocableMethod — https://developer.salesforce.com/docs/ai/agentforce/guide/agent-invocablemethod.html136- Agentforce Actions — https://developer.salesforce.com/docs/ai/agentforce/guide/get-started-actions.html137- Agentforce Metadata Types — https://developer.salesforce.com/docs/ai/agentforce/references/agents-metadata-tooling/agents-metadata.html138- Agentforce Testing Center — https://help.salesforce.com/s/articleView?id=ai.agent_testing_center.htm&type=5