-
Notifications
You must be signed in to change notification settings - Fork 0
Error Handling In‐Depth
The Apex Orbit Framework (AOF) employs a robust and decoupled error handling mechanism designed to capture and log exceptions effectively without impacting the primary transaction flow. This section details the components and processes involved.
-
ErrorLogEvent__e(Platform Event):-
Purpose: Serves as the transport medium for error details. Publishing a platform event is an asynchronous operation that occurs after the successful completion of the current transaction (if
PublishAfterCommitbehavior is used, which is default and recommended) or immediately (ifPublishImmediatelyis used). - Key Fields: As defined in the Setup Guide (Timestamp, TransactionId, OriginatingClassName, ErrorMessage, StackTrace, Severity, etc.).
- Benefit: Decouples error logging from the transaction that caused the error. If the main transaction rolls back due to the error, the platform event (if published after commit and the commit point is reached, or if published immediately) can still be processed, ensuring the error is logged.
-
Purpose: Serves as the transport medium for error details. Publishing a platform event is an asynchronous operation that occurs after the successful completion of the current transaction (if
-
Error_Log__c(Custom SObject):- Purpose: Provides persistent storage for error details. This allows for querying, reporting, and tracking of errors over time.
-
Fields: Mirrors the fields of
ErrorLogEvent__eand adds fields for tracking and management (e.g.,Status__c,AssignedTo__c,ResolutionNotes__c).
-
AOF_ErrorHandlerService.cls(Utility Class):-
Purpose: Provides a centralized and easy-to-use way to publish
ErrorLogEvent__eevents from anywhere in the Apex code. -
Key Methods:
-
logError(Exception ex, String className, String methodName, List<Id> recordIds, String sObjectTypeApiName, String severity): For logging standard Apex exceptions. -
logError(String message, String className, String methodName, List<Id> recordIds, String sObjectTypeApiName, String severity): For logging custom error messages.
-
-
Functionality: Constructs the
ErrorLogEvent__epayload and usesEventBus.publish()to send it. It includes its own internal try-catch to prevent the logging mechanism itself from throwing unhandled exceptions.
-
Purpose: Provides a centralized and easy-to-use way to publish
-
ErrorLogEventSubscriber.trigger(Apex Trigger onErrorLogEvent__e):-
Purpose: Subscribes to the
ErrorLogEvent__eplatform events. -
Functionality: When an
ErrorLogEvent__eis received, this trigger takes the event payload and creates a newError_Log__crecord, saving the error details to the database. This operation is bulkified to handle multiple events efficiently.
-
Purpose: Subscribes to the
- Exception Occurs: An exception is thrown and caught within a try-catch block in a Domain, Service, or Handler class.
-
Call
AOF_ErrorHandlerService: The catch block calls one of the staticlogErrormethods inAOF_ErrorHandlerService.cls, passing relevant details like the exception object, class/method name, involved record Ids, SObject type, and severity. -
Publish Platform Event:
AOF_ErrorHandlerServicecreates an instance ofErrorLogEvent__e, populates its fields, and publishes it usingEventBus.publish(). - Asynchronous Processing: The platform event is added to the event bus.
-
Subscriber Trigger Fires: The
ErrorLogEventSubscriber.trigger(listening toErrorLogEvent__e) fires asynchronously when the event is processed from the bus. -
Create
Error_Log__cRecord: The subscriber trigger extracts the data from theErrorLogEvent__epayload and creates one or moreError_Log__crecords, persisting the error details.
-
User-Facing Errors (Validations): For errors that need to be displayed directly to the user in the Salesforce UI (e.g., validation rule failures), use the
SObject.addError()method (e.g.,myAccount.Name.addError('Account Name cannot be blank.')). This prevents the record from being saved and shows the message to the user. These types of errors typically do not need to be logged viaAOF_ErrorHandlerServiceunless there's a specific requirement to track validation failures. -
System Errors (Exceptions): For unexpected exceptions or system-level errors that users should not directly see as raw exception messages, use the
AOF_ErrorHandlerService. You can then useaddError()with a generic message for the user (e.g.,myAccount.addError('An unexpected error occurred. Please contact support. Ref: ' + errorId);) while the detailed error is logged inError_Log__c.
-
Catch Specific Exceptions: Whenever possible, catch specific exception types (e.g.,
DmlException,QueryException,MathException) rather than just the genericExceptiontype. This allows for more targeted error handling if needed. -
Provide Context: When calling
AOF_ErrorHandlerService.logError(), provide as much context as possible: class name, method name, involved record Ids, SObject type. This greatly aids in debugging. -
Set Appropriate Severity: Use the
severityparameter to indicate the impact of the error (e.g., Critical, High, Medium, Low). This helps in prioritizing error investigation. -
Don't Swallow Exceptions: After logging an error with
AOF_ErrorHandlerService, decide whether to re-throw the exception or handle it gracefully. If the error should cause the current transaction to roll back (which is often the case for unexpected system errors), ensure it does, either by re-throwing or by usingaddError()if in abeforetrigger context. -
Test Error Logging: Include scenarios in your Apex unit tests that specifically trigger exceptions and verify that
ErrorLogEvent__eevents are published correctly (usingTest.startTest(),Test.stopTest()and checking event publishing, or by queryingError_Log__cif testing the subscriber trigger indirectly). -
Monitor
Error_Log__c: Regularly review theError_Log__crecords to identify recurring issues, performance problems, or bugs in your application.

Home
Quick Start
Usage Guide and Examples
Metadata‐Driven Trigger
Best Practices
Core Principles
Framework Architecture and Layers
Trigger Handler Layer
Service Layer
Domain Layer
Selector Layer
Unit of Work Layer
Error Handling Framework
Trigger Execution Flow
Scalability and Performance
Security Considerations
Core Components In-Depth
Error Handling In-Depth
Customization and Extension