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.
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.
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).
Error:
System.LimitException: Too many DML statements: 151
Solution:
- Perform DML operations in bulk, not one-by-one.
- Minimize updates/inserts inside loops.
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.
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.
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.
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.
Error:
Maximum trigger depth exceeded
Solution:
- Implement static variables or custom logic to prevent recursion.
- Always check for context before updating records in triggers.
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.
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!
Post a Comment