Error Handling in Apex: Writing Robust and Maintainable Code – Salesforce

Error Handling and Writing Robust, Maintainable Code in Salesforce
Chinmaya By Chinmaya
6 Min Read

Introduction

Error handling is a critical aspect of writing reliable and maintainable Apex code in Salesforce. Proper error handling not only ensures that your application behaves predictably during unexpected events but also makes debugging and maintenance significantly easier.

In this blog, we will explore best practices and techniques for handling errors in Apex effectively.

    • Importance of error handling in Salesforce Apex.
    • How robust error handling improves system reliability and maintainability.
    • Brief overview of what the blog will cover.

Why Error Handling Matters in Apex?

Error handling is crucial for several reasons:

    1. System Stability: Prevents unhandled exceptions from crashing the system.
    2. User Experience: Provides meaningful feedback to users instead of cryptic error messages.
    3. Debugging Ease: Helps developers quickly pinpoint issues by logging and monitoring errors.
    4. Compliance: Ensures adherence to business rules and workflows.

Understanding Apex Exception Types

    1. System Exceptions:
      Errors like NullPointerException, DmlException, QueryException, and LimitException that occur due to system-level issues.

    2. Custom Exceptions:
      Application-specific errors triggered by custom logic, such as validation failures.

    3. Governor Limits Exceptions: Errors due to exceeding Salesforce governor limits, like SOQL query limits or CPU timeouts.

Examples:

				
					try {
    Account acc = [SELECT Id FROM Account WHERE Name = 'NonExistent'];
} catch (QueryException e) {
    System.debug('Query Exception occurred: ' + e.getMessage());
}

// Custom exception example
public class CustomException extends Exception {}
				
			

Best Practices for Error Handling in Apex

1. Use Try-Catch Blocks

Encapsulate risky code within try-catch blocks to handle exceptions gracefully.

				
					try {
    Account acc = new Account(Name = null); // Causes a required field exception
    insert acc;
} catch (DmlException e) {
    System.debug('Error inserting Account: ' + e.getMessage());
}
				
			

2. Handle Specific Exceptions

Catch specific exceptions to provide tailored responses instead of using generic error handling.

				
					try {
    List<Account> accounts = [SELECT Id, Name FROM Account WHERE Name = 'Nonexistent'];
} catch (QueryException qe) {
    System.debug('Query failed: ' + qe.getMessage());
} catch (Exception ex) {
    System.debug('General exception: ' + ex.getMessage());
}
				
			

3. Custom Exceptions

Create custom exceptions for domain-specific errors, making the code easier to debug and maintain.

				
					public class InvalidDataException extends Exception {}

public static void validateData(String input) {
    if (String.isBlank(input)) {
        throw new InvalidDataException('Input cannot be blank.');
    }
}
				
			

4. Bulk Error Handling

In bulk operations, handle partial failures by leveraging the Database class’s saveResult and upsert methods.

				
					List<Account> accounts = new List<Account>{
    new Account(Name = 'Test1'),
    new Account(Name = null) // This will cause a failure
};

Database.SaveResult[] results = Database.insert(accounts, false);
for (Database.SaveResult result : results) {
    if (!result.isSuccess()) {
        System.debug('Error: ' + result.getErrors()[0].getMessage());
    }
}
				
			

5. Logging Errors

Log errors in a custom object or use Salesforce’s built-in logging tools (like the Apex Debug Log) for better traceability.

				
					public static void logError(Exception e) {
    Error_Log__c log = new Error_Log__c();
    log.Message__c = e.getMessage();
    log.StackTrace__c = e.getStackTraceString();
    insert log;
}
				
			

6. Governor Limits Awareness

Handle governor limit exceptions proactively. For instance, use efficient queries and avoid SOQL/DML inside loops.

				
					try {
    List<Contact> contacts = [SELECT Id, Name FROM Contact LIMIT 50000];
} catch (LimitException le) {
    System.debug('Governor limit exceeded: ' + le.getMessage());
}
				
			

If you’re not familiar with Governor Limits in Salesforce, I highly recommend exploring the post linked below.
Understanding the Governor Limit concept is crucial for developers and also it is a commonly asked interview question.

7. Asynchronous Error Handling

For future methods and asynchronous Apex, use custom logging or platform events to capture errors since exceptions cannot be returned to the calling context.

				
					@future
public static void asyncMethod() {
    try {
        // Some code
    } catch (Exception e) {
        // Log error in a custom object or via platform events
    }
}
				
			

Common Mistakes to Avoid

1. Swallowing Exceptions:

Avoid empty catch blocks as they obscure errors and make debugging difficult.

				
					try {
    // Risky code
} catch (Exception e) {
    // Do nothing - Bad practice
}
				
			

2. Hardcoding Error Messages:

Use custom labels for error messages to make the application adaptable to localization.

3. Overusing Try-Catch:

Instead of overloading the code with try-catch blocks, validate inputs and preconditions to avoid exceptions in the first place.

Now that you’ve learned how to handle errors in an Apex class, let’s explore the best practices every developer should follow while writing Apex code.

Check out the post below to learn more!

Conclusion

Error handling in Apex is not just about catching and logging exceptions but also about writing proactive and resilient code.
By following best practices such as using specific exception handling, custom exceptions, and proper logging mechanisms, Salesforce developers can ensure that their code is robust, maintainable, and user-friendly.

Apex is a powerful language, and mastering error handling will make your applications more reliable while providing a seamless experience for users and admins alike.

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
1 Comment