exception-handling

Use when writing, reviewing, or debugging Apex exception handling, DmlException behavior, custom exception hierarchies, or user-safe error messages. Triggers: 'DmlException', 'swallowed exception', 'AuraHandledException', 'trigger rollback', 'try catch'. NOT for choosing async execution models or general governor-limit tuning.

Best use case

exception-handling is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Use when writing, reviewing, or debugging Apex exception handling, DmlException behavior, custom exception hierarchies, or user-safe error messages. Triggers: 'DmlException', 'swallowed exception', 'AuraHandledException', 'trigger rollback', 'try catch'. NOT for choosing async execution models or general governor-limit tuning.

Teams using exception-handling should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/exception-handling/SKILL.md --create-dirs "https://raw.githubusercontent.com/PranavNagrecha/AwesomeSalesforceSkills/main/skills/apex/exception-handling/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/exception-handling/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How exception-handling Compares

Feature / Agentexception-handlingStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Use when writing, reviewing, or debugging Apex exception handling, DmlException behavior, custom exception hierarchies, or user-safe error messages. Triggers: 'DmlException', 'swallowed exception', 'AuraHandledException', 'trigger rollback', 'try catch'. NOT for choosing async execution models or general governor-limit tuning.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

Use this skill when Apex error handling is becoming part of the design, not just a syntax exercise. The goal is to prevent swallowed failures, preserve operational visibility, and return the right kind of error for the calling context without corrupting bulk processing.

## Before Starting

- What is the entry point: trigger, controller, REST resource, Queueable, Batch, invocable, or scheduled job?
- Should one bad record fail the whole transaction, or is partial success acceptable?
- Where do production failures go today: custom log object, platform event, observability tool, or nowhere?

## Core Concepts

### Catch Expected Failures, Not Everything

Apex supports standard exception types such as `DmlException`, `QueryException`, and `CalloutException`, plus custom exceptions. Catch the most specific exception you can actually handle. Salesforce guidance is to catch expected exceptions, add context, and let unexpected exceptions propagate instead of masking the root cause. A blanket `catch (Exception e)` that returns `null` or `false` usually turns a debuggable failure into silent data loss.

### Bulk DML Failure Semantics Matter

`insert records;` and `update records;` throw a `DmlException` on failure and stop the transaction. `Database.insert(records, false)` and `Database.update(records, false)` behave differently: they allow partial success and return `Database.SaveResult[]`. In bulk code, this choice is architectural. If the business process can tolerate some failures, inspect `SaveResult` per record and log or surface the rejected records. Do not wrap a whole bulk update in one `try/catch` and assume that makes it bulk-safe.

### Boundary-Specific Error Translation

Different Apex boundaries need different failure behavior. In a trigger, business-rule failures generally belong on the record through `addError`, while unexpected exceptions should surface and roll back the transaction. In an Aura/LWC controller, raw system messages are poor UX, so map known failures to `AuraHandledException` with a human-safe message. In background jobs, user messaging is irrelevant; logging and retry classification matter more.

### Log Once, At The Right Layer

Centralize logging at a service boundary or integration boundary. If every layer catches and logs the same exception, production monitoring fills with duplicates and the real signal disappears. Prefer a single structured log entry containing the operation, record IDs or correlation ID, failure type, and whether the exception was rethrown or transformed.

## Common Patterns

### Specific Catch With Domain Mapping

**When to use:** A service class knows how to turn a low-level Salesforce failure into a business-facing failure.

**How it works:** Catch `DmlException` or `CalloutException`, log structured context once, then throw a domain-specific exception or boundary-safe exception such as `AuraHandledException`.

**Why not the alternative:** Catching generic `Exception` in every layer hides the original failure and produces inconsistent messages.

### Partial Success For Bulk Operations

**When to use:** A batch-like service should process as many records as possible even if some fail validation.

**How it works:** Use `Database.insert/update/delete(records, false)`, inspect every `SaveResult`, and store or return the failed record IDs and messages.

**Why not the alternative:** A single `update records;` statement plus one catch block loses per-record visibility and fails the entire transaction.

### Trigger Business Validation With `addError`

**When to use:** The user should be told exactly which record violates a business rule during DML.

**How it works:** Add errors to offending records in trigger context for expected business validation failures. Reserve thrown exceptions for truly unexpected or system-level faults.

## Decision Guidance

| Situation | Recommended Approach | Reason |
|---|---|---|
| User-facing controller needs a safe error message | Catch the specific exception and map it to `AuraHandledException` | Preserves UX while avoiding raw internal messages |
| Trigger validation should block a save for a known business rule | Use `record.addError()` | Keeps the error attached to the record and fits trigger semantics |
| Bulk service can accept partial success | Use `Database.*(list, false)` and inspect `SaveResult[]` | Avoids one bad record failing the whole batch |
| Unexpected null pointer or design bug | Let it bubble after optional boundary logging | Hidden defects are harder to fix than loud failures |


## Recommended Workflow

Step-by-step instructions for an AI agent or practitioner activating this skill:

1. Gather context — confirm the org edition, relevant objects, and current configuration state
2. Review official sources — check the references in this skill's well-architected.md before making changes
3. Implement or advise — apply the patterns from Core Concepts and Common Patterns sections above
4. Validate — run the skill's checker script and verify against the Review Checklist below
5. Document — record any deviations from standard patterns and update the template if needed

---

## Review Checklist

- [ ] Catch blocks are specific; generic `catch (Exception e)` is justified or removed.
- [ ] No catch block silently returns success, `null`, or `false` without logging or rethrowing.
- [ ] Bulk DML paths use `SaveResult[]` when partial success is required.
- [ ] Trigger code uses `addError` for expected business validation, not generic swallowed exceptions.
- [ ] User-facing controllers return safe, human-readable messages instead of raw internal stack traces.
- [ ] Logging happens once with operation context, record scope, and failure type.

## Salesforce-Specific Gotchas

1. **Unhandled trigger exceptions roll back the transaction** — if a trigger throws unexpectedly, the entire DML operation fails, including unrelated records in the same transaction.
2. **`Database.update(list, false)` does not throw for every row failure** — record-level failures move into `SaveResult[]`; if you never inspect those results, you silently lose failures.
3. **`AuraHandledException` is a boundary tool, not a service-layer base class** — using it deep in service code couples business logic to UI transport concerns.
4. **A debug-only catch block is effectively a swallowed exception** — `System.debug` is not monitoring, and production users never see it.

## Output Artifacts

| Artifact | Description |
|---|---|
| Exception handling review | Findings on swallow risks, bulk failure behavior, and boundary-appropriate error translation |
| Remediation pattern | Recommended catch, log, rethrow, or `addError` structure for the current context |
| Failure classification matrix | Expected vs unexpected failures with the correct handling strategy per entry point |

## Related Skills

- `apex/async-apex` — use when the real fix is moving work to Queueable, Batch, or Scheduled Apex instead of trapping errors in a synchronous transaction.
- `apex/test-class-standards` — use alongside this skill to verify negative-path assertions, exception expectations, and mock-based error scenarios.
- `apex/trigger-framework` — use when trigger structure is making exception handling chaotic or duplicated across multiple handlers.

Related Skills

omnistudio-error-handling-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing fault behavior across Integration Procedures, DataRaptors, OmniScripts, and FlexCards — error routing, user-facing messaging, retry semantics, and idempotency. Triggers: 'omnistudio error', 'integration procedure fault', 'dataraptor error handling', 'omniscript retry', 'flexcard action failure'. NOT for general Apex exception design or Flow fault paths.

lightning-navigation-dead-link-handling

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when an LWC navigates via NavigationMixin to records or pages that may no longer exist, lack the user's access, or be permanently moved. Triggers: 'lightning navigation 404', 'navigate to deleted record', 'NavigationMixin error toast', 'graceful fallback when target page missing', 'permission denied on navigation'. NOT for general routing within an SPA or for Experience Cloud public-facing routing.

error-handling-in-integrations

8
from PranavNagrecha/AwesomeSalesforceSkills

Use this skill to design orchestration-layer error handling for Salesforce integrations — covering Platform Event replay recovery, dead-letter queue routing, cross-channel error notification patterns, circuit breaker design, and trigger suspension recovery. Trigger keywords: integration error handling, Platform Event retry, integration dead letter queue, EventBus RetryableException, integration circuit breaker, event bus trigger suspended. NOT for Apex exception handling (use apex-exception-handling skill), HTTP error response contracts (use api-error-handling-design), or retry backoff patterns (use retry-and-backoff-patterns).

api-error-handling-design

8
from PranavNagrecha/AwesomeSalesforceSkills

Designing HTTP error classification, RFC 7807-style error payload structure, and client-side error parsing for Salesforce REST/SOAP integrations and custom Apex REST endpoints. Use when deciding which HTTP status codes to return from custom Apex REST services, how to structure error response bodies, how to classify inbound API errors as retry-safe vs non-retry-safe, or how to parse Salesforce error responses on the consumer side. NOT for retry execution mechanics or circuit breaker implementation (use retry-and-backoff-patterns). NOT for Apex exception class design (use apex-error-handling-framework). NOT for OAuth error flows (use oauth-flows-and-connected-apps).

fault-handling

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing, reviewing, or troubleshooting Salesforce Flow fault handling, error logging, and bulk-safe automation paths. Triggers: 'fault connector', '$Flow.FaultMessage', 'flow failed', 'record-triggered flow rollback', 'screen flow error'. NOT for generic Flow type selection unless the main risk is failure handling; NOT for Apex exception handling (see apex/exception-handling-patterns).

error-handling-framework

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or implementing a cross-cutting Apex error handling framework: custom exception hierarchies, rollback-safe logging via Platform Events, BatchApexErrorEvent processing, correlation ID threading, or a unified catch/log/rethrow utility class. Trigger keywords: 'error framework', 'centralized logging', 'rollback-safe log', 'BatchApexErrorEvent', 'correlation ID async', 'AuraHandledException boundary', 'Error_Log__c design'. NOT for individual try/catch block syntax help, basic DmlException handling, or choosing between synchronous and asynchronous execution models.

xss-and-injection-prevention

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when writing or reviewing Visualforce pages, Apex controllers, or LWC components that output user-supplied data, build dynamic queries, or construct HTTP responses. Triggers: 'XSS in Visualforce', 'SOQL injection vulnerability', 'how to encode output in Apex', 'JSENCODE Visualforce', 'open redirect prevention'. NOT for Apex CRUD/FLS enforcement (use soql-security or apex-crud-and-fls), NOT for Shield encryption (use shield-encryption-key-management), NOT for AppExchange security review process (use secure-coding-review-checklist).

visualforce-security-and-modernization

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when hardening or modernizing legacy Visualforce pages — covers the platform CSRF token model and when disabling it is a security regression, view state encryption guarantees and the 170 KB ceiling, FLS/CRUD enforcement gaps on `<apex:outputField>` and on getters that return sObjects, `<apex:includeScript>` interaction with the org Content Security Policy, hosting LWC inside a VF page via `lightning:container` / `lightning-out`, and the retire-vs-harden-vs-leave-alone decision for an inventory of legacy pages. Triggers: 'should I rewrite this Visualforce page in LWC', 'CSRF protection disabled on Visualforce page is that safe', 'community user sees a field they should not on a Visualforce page', 'view state encryption is that enough for sensitive data', 'how do I host an LWC inside a Visualforce page', 'apex:dynamicComponent and apex:actionFunction safe to keep'. NOT for greenfield Visualforce architecture (use apex/visualforce-fundamentals — controller types, view state pattern selection, PDF rendering); NOT for Visualforce email template authoring (use apex/visualforce-email-templates if/when that skill is authored); NOT for general Apex security review across triggers and async (use apex/soql-security and security/secure-coding-review-checklist).

transaction-security-policies

8
from PranavNagrecha/AwesomeSalesforceSkills

Transaction Security policy creation and configuration: condition builder, enhanced policies, enforcement actions (block, MFA, notification, end session), real-time monitoring mode, and policy troubleshooting. NOT for Event Monitoring log analysis or Shield Event Monitoring setup (use event-monitoring). NOT for Apex testing or debug-log analysis.

sso-saml-troubleshooting

8
from PranavNagrecha/AwesomeSalesforceSkills

Diagnosing broken SAML SSO into Salesforce — IdP-initiated vs SP-initiated flows, signing-certificate validity / expiry, NameID format mismatches, RelayState handling, audience / entityId / issuer mismatches, clock skew, the SAML Assertion Validator in Setup, the Login History debug log, and the My Domain prerequisite for SSO. Covers the standard diagnostic loop: read the SAML response, identify which check failed, fix at the IdP or SP. NOT for OAuth / OpenID Connect SSO (see security/oauth-openid-troubleshooting), NOT for setting up SSO from scratch (see security/sso-saml-setup).

shield-kms-byok-setup

8
from PranavNagrecha/AwesomeSalesforceSkills

Configure Shield Platform Encryption with customer-supplied (BYOK) or customer-held (Cache-Only Key Service) tenant secrets, rotate them, and recover. NOT for Classic Encryption or field masking.

shield-event-log-retention-strategy

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing Salesforce Shield Event Monitoring retention, SIEM routing, and storage-tier strategy — which event types to keep, for how long, where, and how to answer audit queries across hot/warm/cold tiers. Triggers: 'shield event log retention', 'route event monitoring to splunk', 'how long to keep login history', 'siem salesforce integration', 'event monitoring storage tier'. NOT for enabling Shield (see salesforce-shield-deployment).