In Salesforce Apex, handling errors effectively is crucial for debugging and maintaining a robust application. When an error occurs, it’s important to log the details to help track the issue and provide the necessary context for resolution. This becomes even more essential when working with complex integrations or data processing, where errors can arise from external system failures, incorrect data inputs, or unexpected application behavior.
This blog post explores a structured approach to error handling in Apex by implementing proper exception capturing and logging mechanisms. The objective is to ensure that errors are not only caught but also stored systematically for future reference and troubleshooting.
Why Error Handling Matters
Enhanced Debugging: Capturing error details like stack traces and request parameters helps in identifying the root cause of issues quickly.
Data Integrity: Handling errors properly ensures that transactions remain consistent and do not leave data in a corrupted state.
Improved User Experience: Providing meaningful error messages or fallback mechanisms enhances user trust and reduces frustration.
Compliance and Auditing: Logging errors systematically ensures that critical failures are recorded, which is essential for compliance and audit purposes.
Creating the Error Log Object and Fields
To store error logs systematically, we need to create a custom object in Salesforce named Error_Log__c
. Follow these steps to set it up:
Step 1: Create a Custom Object
Navigate to Setup → Object Manager.
Click New Custom Object.
Enter Label:
Error Log
Enter Plural Label:
Error Logs
Enter API Name:
Error_Log__c
Enable Allow Reports and Track Field History if needed.
Click Save.
Step 2: Add Custom Fields
Error Line Number (
Error_Line_Number__c
)Data Type: Number
Description: Stores the line number where the error occurred.
Request Parameters (
Request_Param__c
)Data Type: Text (255)
Description: Captures request details for debugging.
Error JSON (
Error_Json__c
)Data Type: Long Text Area
Description: Stores JSON payloads for additional error details.
Stack Trace (
Stack_Trace__c
)Data Type: Long Text Area
Description: Stores error messages and stack traces.
Error Method (
Error_Method__c
)Data Type: Text (100)
Description: Captures the method where the error occurred.
Error Class (
Error_Class__c
)Data Type: Text (100)
Description: Captures the class where the error occurred.
Once these fields are created, they will be used in our Apex error handling implementation.
Implementing Error Handling and Logging in Apex
Below is an Apex method that demonstrates best practices for error handling and logging. The method initializes an error log list, captures exceptions, logs error details, and ensures that logs are stored in the Error_Log__c
object.
public class ErrorHandlingExample {
global static void methodname() {
List<Error_Log__c> listErrorLogs = new List<Error_Log__c>(); // Initialize the error log list
try {
System.debug('-- start --'); // Debugging message to show the start of the method's execution
// Simulated logic that may throw an exception
Integer result = 5 / 0; // This will cause a divide by zero error
} catch (Exception e) {
// Creating an error log entry
Error_Log__c elogs = new Error_Log__c(
Error_Line_Number__c = e.getLineNumber(),
Request_Param__c = 'sampleRequestParam', // Example placeholder for request parameters
Error_Json__c = '{"sample": "jsonPayload"}', // Example JSON payload
Stack_Trace__c = e.getMessage() + ' Stack trace :' + e.getStackTraceString(),
Error_Method__c = 'methodname',
Error_Class__c = 'ErrorHandlingExample'
);
listErrorLogs.add(elogs); // Add the error log to the list
System.debug('Error in ErrorHandlingExample @ line number ' + e.getLineNumber() + ' error message ' + e.getMessage());
} finally {
// Upsert the error logs if there are any entries
if (!listErrorLogs.isEmpty()) {
upsert listErrorLogs; // Upsert the error logs into the database
}
}
}
}
Best Practices for Error Logging in Apex
- Use Custom Error Log Objects: Storing logs in Salesforce objects allows for querying and reporting.
- Include Relevant Context: Capturing method names, class names, request parameters, and stack traces improves troubleshooting.
- Avoid Hardcoded Values: Ensure error messages are dynamically generated from actual exceptions.
- Use Debug Logs Wisely: While
System.debug()
is helpful for development, avoid overusing it in production. - Handle Governor Limits: If logging in bulk operations, consider asynchronous processing (e.g., Queueable Apex) to avoid exceeding limits.
Conclusion
Effective error handling and logging in Apex is crucial for building reliable and maintainable applications. By capturing errors systematically and storing relevant details, developers can quickly diagnose issues, maintain data integrity, and improve overall application robustness. Implementing structured error logging as demonstrated in this blog ensures that failures are detected and addressed proactively, minimizing business disruptions.
By following these best practices, Salesforce developers can enhance application reliability and ensure seamless user experiences while keeping critical error logs accessible for troubleshooting and audit purposes.