Common Salesforce Apex Errors & Solutions

 Apex development comes with its own set of challenges. Here are some frequent errors you may encounter, along with practical solutions to help you debug and resolve them quickly.


1. SOQL Query Limit Exceeded

Error:

System.LimitException: Too many SOQL queries: 101

Solution:

  • Bulkify your code—avoid SOQL queries inside loops.
  • Consolidate queries and retrieve related data in one go.

2. CPU Time Limit Exceeded

Error:

System.LimitException: Apex CPU time limit exceeded

Solution:

  • Optimize logic and avoid unnecessary looping.
  • Use efficient collections (Map, Set).
  • Move long-running tasks to asynchronous processes (Batch, Queueable).

3. DML Statement Limit Exceeded

Error:

System.LimitException: Too many DML statements: 151

Solution:

  • Perform DML operations in bulk, not one-by-one.
  • Minimize updates/inserts inside loops.

4. Attempt to de-reference a null object

Error:

System.NullPointerException: Attempt to de-reference a null object

Solution:

  • Check for null before accessing object fields or methods.
  • Use safe navigation (?.) operator where possible.

5. Mixed DML Operation Error

Error:

System.DmlException: DML operation on setup object is not permitted after you have performed DML on non-setup object

Solution:

  • Separate DML operations for setup (User, Profile, etc.) and non-setup objects in different transactions.
  • Use @future methods for setup object DML after non-setup DML.

6. FIELD_INTEGRITY_EXCEPTION

Error:

FIELD_INTEGRITY_EXCEPTION, field is not writeable

Solution:

  • Check Field Level Security (FLS) and object permissions.
  • Ensure the field is editable for the running user.

7. Too Many Uncommitted Work Pending Errors

Error:

System.UnexpectedException: Too many uncommitted work pending

Solution:

  • Avoid multiple callouts, DML, or email sends in the same transaction.
  • Refactor logic into asynchronous methods if needed.

8. Recursive Trigger Error

Error:

Maximum trigger depth exceeded

Solution:

  • Implement static variables or custom logic to prevent recursion.
  • Always check for context before updating records in triggers.

9. UNABLE_TO_LOCK_ROW

Error:

UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record

Solution:

  • Use FOR UPDATE in SOQL for record locking.
  • Review and avoid simultaneous updates to the same records.

10. Malformed Query/Invalid Field

Error:

System.QueryException: No such column 'FieldName' on entity 'ObjectName'

Solution:

  • Double-check field and object API names.
  • Use Schema Explorer or describe calls to validate fields.

Pro Tip:
Always use meaningful exception handling and logging to make error diagnosis easier!

0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post