Simplifying Salesforce Error Logging with Platform Events

Ranjan Singh
4 min readJun 2, 2024

--

Introduction

Error logging is a critical aspect of maintaining robust and reliable applications in Salesforce. Traditional error logging methods, particularly within trigger contexts and batch Apex operations, often fall short due to transactional limitations. This blog explores a modern approach to error logging using Platform Events, offering a scalable and asynchronous solution that overcomes these challenges. By the end of this article, you’ll understand how to implement this framework and leverage Platform Events for efficient error management in Salesforce.

Problem Statement in Legacy Error Logging

Issues with Traditional Error Logging

In Salesforce triggers, performing a rollback using the throw statement from a catch block prevents error logs from being stored due to the rollback of all DML operations. Here’s an example:

try {
insert new Account();
} catch (Exception ee) {
logException(ee);
throw ee; // Error logging DML will also be rolled back
}

Challenges

  • Rollback of Error Logs: If you want to throw an exception on the UI and need to log the error, this approach fails. Any DML operation before the throw statement in a try-catch block will also be rolled back. In the above example, logException(ee) will be rolled back along with the Account insertion.
  • Database.rollback does not function for trigger context sObjects.
  • Apex Job Log: It’s impossible to determine if batch jobs are successful since all caught exceptions are reported as “success.”
  • Additional DML Operations: Traditional methods require an additional DML operation within the same transaction, leading to potential data integrity issues.

Potential Solutions

To overcome these challenges, error logging needs to occur in a separate transaction from the main business logic.

Ineffectiveness of Future Methods

Future jobs queued by a transaction aren’t processed if the transaction rolls back, making them unreliable for error logging in rolled-back transactions.

Error Logging Using Platform Events

Platform Event Architecture

Platform Events operate on an event bus-driven architecture, providing an asynchronous thread model. They run in a separate transaction from the one that fired them, resetting governor limits and giving the event trigger its own set of limits. By setting the publish behavior to “Publish Immediately,” the event message is guaranteed to be published regardless of whether the synchronous transaction succeeds.

Salesforce Platform Event-Driven Architecture Flow Diagram

Workflow for Error Logging Using Platform Events

  1. Error Occurrence: An error is caught in the application code.
  2. Error Data Preparation: Error details are formatted into a log event payload.
  3. Platform Event Creation: The appropriate platform event is created based on the error type.
  4. Publish Platform Event: The event is published to the Platform Event Bus.
  5. Event Triggers and Subscribers: Subscribers process and store the error data in custom objects, logs, or external systems.

Benefits of Using Platform Events for Error Logging

  • Asynchronous Logging: Reduces performance impact on the main application logic.
  • Real-time Monitoring: Enables immediate detection and analysis of issues.
  • Centralized Error Data: Provides a unified repository for error logs.
  • Scalability: Handles high volumes of error data.
  • Customizable Error Data: Supports flexible error data structures.
  • Governor Limits Isolation: Ensures separate transactions for event triggers.

Types of Platform Events in the Logging Framework

BatchApexErrorEvent

Logs errors during Batch Apex executions. Implementing Database.RaisesPlatformEvents in a batch class declaration allows capturing these errors, including LIMIT exceptions. Implementing this interface will implicitly fires a platform event in case of transaction failure in batch apex processing at any phase(start, execute, finish). Example:

public with sharing class SamplePlatformEventBatch implements Database.Batchable<SObject>, Database.RaisesPlatformEvents {
// Batch logic here
}

FlowExecutionErrorEvent

Captures errors in screen flow executions. Note: This is not applicable to autolaunched flows or processes after API version 48.0.

Custom Platform Events

Designed for logging specific errors from Apex Triggers, Controllers, and Screen Flows with fault screens.

try {
// Error generated
} catch (QueryException qe) {
GenericErrorLoggerClass.logException(qe, 'AccountTrigger');
} catch (DMLException de) {
GenericErrorLoggerClass.logException(de, 'AccountTrigger');
} catch (Exception ee) {
GenericErrorLoggerClass.logException(ee, 'AccountTrigger');
}

Process Flow

Event Delivery Limitation

For event delivery limitations, follow this guideline. Non-CometD clients, including Apex triggers, processes, and flows, do not count against the event delivery limit. Processing time for each subscriber influences the speed at which the subscriber reaches the event stream tip.

Conclusion

Using Platform Events for error logging in Salesforce offers a robust, scalable, and asynchronous solution that overcomes the limitations of traditional error logging methods. By isolating governor limits and handling high volumes of error data, Platform Events ensures reliable and efficient error management.

For more details and to access the complete code, refer to the GitHub repository.

--

--

Ranjan Singh

9x Salesforce Certified, A Certified Application Architect, Salesforce Technical Lead