1.Mixed DML Operation Error: 

Reason: When you try to combine DML operations for both Setup and Non-Setup objects in a same transaction (Where Setup objects such as Group, Group member, Queue SObject, User. Non-Setup Objects such as Standard and Custom Objects).

Resolution: We can use @future annotation to do DML operation. It will split the transactions.

Another approach is to use same logic in a batch class to overcome.

2.Cpu time limit exceed: 

Reason 1: Based on CPU usage, Salesforce has a timeout limit for each transaction. Due to consumption of too much CPU time limit in a transaction, this error could occur.

Reason 2: If you use nested for-loop (for-loop inside another for-loop), then you must use Map(s) to resolve the issue, as it is one of the common reasons for CPU Time Limit

For 
{  for  {  } 
}

Counted:  

  • All Apex Code.
  • Workflow execution.
  • Library functions exposed in Apex.

Not Counted:  

  • Database Operations (DML)
  • SOSL
  • SOQL
  • HTTP Callouts.

3.System.QueryException: Non-selective query against large object type: 

Reason: If you query records on object that returns more than 200,000 records and without query filters, it’s possible that you’ll receive the error, “System.QueryException: Non-selective query against large object type.” We’ll go over the a few possible fixes.

Resolution: It’s best to try to have that field indexed by checking the “external ID” checkbox when you create that field.  Also, as a best practice, always use WHERE clause in your SOQL statements to read the records.

Example: [Select id, Name, Type from Account WHERE Type = “Prospect”];

Finally, filter out all null records in your Apex query.

4.Too many SOQL Queries: 

Reason: We can run up to a total of 100 SOQL queries in a single transaction or context. All the SOQL queries in triggers fired from one call or context will be counted against the limit of 100.  When the number of SOQL queries exceed the limit in a single transaction, then this error is thrown by Salesforce.

Resolution: To fix this issue, you’ll need to change your code in such a way that the number of SOQL fired is less than 100. If you need to change the context, then you can use @future annotation which will run the code asynchronously. Here are some best practices that will stop the error messages.

Governor Limit:
1. Since Apex runs on a multi-tenant platform, the Apex runtime engine strictly enforces limits to ensure code doesn’t monopolize shared resources. Learn about the Governor Limits

2. Avoid SOQL queries that are inside for loops.
3. Check out the Salesforce Developer Blog where you can find Best Practices for Triggers.
4. Review best practices for Trigger and Bulk requests on our Force.com Apex Code Developer’s Guide.
5. Be sure you’re following the key coding principals for Apex Code in our Developer’s Guide.

Important: Salesforce cannot disable the Governors Limit or raise it. Following the best practices above should ensure that you don’t hit this limit in the future.

5.Non-recursive Parameterized interface method generating infinite recursion error: “Maximum stack depth reached: 1001”:

Reason 1: Let’s say in ‘after update’ trigger, a Developer is performing update operation and this leads to recursive call.

Resolution: We can create a class with a static Boolean variable with default value true. In the trigger, before executing your code keep a check that the variable is true or not. After you check, make the variable as false.

Example Code:  

Class:   public class ContactTriggerHandler  {  public static Boolean isFirstTime = true;  }  Trigger:  trigger ContactTriggers on Contact (after update)  {  Set<String> accIdSet = new Set<String>();   if(ContactTriggerHandler.isFirstTime)  {  ContactTriggerHandler.isFirstTime = false;  for(Contact conObj : Trigger.New)  {  if(conObj.name != 'Test')   {  accIdSet.add(conObj.accountId);  }  }  // any code here  } } 

6. Too many Query rows: 

Reason:  The exception is being thrown because the maximum number of rows we can return in SOQL calls in Apex is 50000.

Resolution: Limit the query results by adding limit. If you want to insert additionally, you will need to use Batch Apex in which the 50K limit counts per batch execution. This limit Counts for each transaction and these limits are reset for each execution of a batch of records in the execute method.

7. Error: System.ListException: List index out of bounds: 0

Reason: Our Query has returned no records that match the criteria. If you then attempt to access an element at row 0, this will throw an error as that row doesn’t exist.

Resolution: Initially Always Check whether the list has records or not.

Error Code:

List<custom obj__c> lrecords=[select Id,name from custom obj__c  ];  lrecords[0].Fileld1__c=2;  lrecords[0].Fileld2__c=3; 
update lrecords;  Modified Code:  List<custom obj__c> lrecords=[select Id,name from custom obj__c  ];  If(lrecords.size()>0)  {  lrecords [0].Fileld1__c=2;  lrecords[0].Fileld2__c=3; 
update lrecords;  } 

8. Error: Sobject row was retrieved via SOQL without querying the requested field:

Reason: This Error is caused by using the field that is not queried in the SOQL query.

Wrong Code:  

Code: Id ids = ‘0012800001EOUIl’;  List<Contact> c =new list<Contact>([Select id from Contact WHERE id =” ids]);  String Conname = c[0].Name;  System.Debug(‘@@@@’+c[0].id);  Resolution: We must add the field name in the query.  Modified Code:   Id ids = ‘0012800001EOUIl’;  List<Contact> c =new list<Contact>([Select id,name from Contact WHERE id =” ids]);  String Conname = c[0].Name;  System.Debug(‘@@@@’+c[0].id); 

9. System.QueryException: List has no rows for assignment to SObject:

Reason: This error is caused when the query cannot get the results back.

Resolution:  

Id ids = null’;  Contact c = [Select id,name from Contact WHERE id =” ids];  System.Debug(‘@@@@’+c.id);  Modified Code:  Id ids = ‘Null’;  If(ids!=Null)  {  Contact  c = [Select id,name from Contact WHERE id =” ids];  System.Debug(‘@@@@’+c.id);  } 

10. System.AsyncException: Rate Limiting Exception: AsyncApexExecutions Limit exceeded:  

Reason: This error occurs when we are hitting an org-wide 24 hour rolling limit on asynchronous Apex.
The maximum number of asynchronous Apex method executions (batch Apex, future methods, Queueable Apex, and scheduled Apex) per a 24-hour period: 250,000 or the number of user licenses in your organization multiplied by 200– whichever is greater”.

11. System.AsyncException: Maximum callout depth has been reached:  

Reason: Queueable Apex Limits

The execution of a queued job counts against the shared limit for asynchronous Apex method executions.

Resolution: 

  • You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction.
  • No limit is enforced on the depth of chained jobs, which means that you can chain one job to another job and repeat this process with each new child job to link it to a new child job. For Developer Edition and Trial organizations, the maximum stack depth for chained jobs is 5, which means that you can chain jobs four times and the maximum number of jobs in the chain is 5, including the initial parent queueable job.
  • When chaining jobs, you can add only one job from an executing job with System.enqueueJob, which means that only one child job can exist for each parent queueable job. Starting multiple child jobs from the same queueable job isn’t supported.

12.System.DmlException: Insert failed. First exception on row2; firsterrorINSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []:

Reason: This error normally happens when a DML operation is performed with a wrong record Id.

13.System.NullPointer Exception: Attempt to Dereference a null object:

Reason: If we use the collections without initializing and if we use any methods of a null object or refer a null variable, null pointer or object exception will occur.

Sample Code:

List<Contact> contactList;  Contact contactIns = new Contact();  ContactIns.LastName = 'test';  ContactList.add(contactIns ); 

14.Error: Invalid Data.:  Apex trigger Acc caused an unexpected exception, contact your administrator: Acc: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0 with id 0032800000vimdqAAA; first

error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]: Trigger.Acc: line 11, column 1:

Reason: While inserting a record in Trigger. the dml should be outside the for loop.

Sample Code:

This is the wrong code:

trigger Acc on Account (after insert) {  List<Contact> ListCont =New List<Contact>();  for(Account acnt : Trigger.New){  for(integer i=0;i<3;i++){  Contact Cont=new Contact();  cont.Lastname=acnt.name+'ContApex1';  cont.accountid=acnt.id;  ListCont.add(cont);  insert ListCont;      } } }  

15.Error: Record is Read only:

Reason: When you are doing an After trigger, Trigger.new is read only. If you want to make changes to it, then it is best to do it in a Before trigger.

Also, your trigger is not bulkified. If more than one record is updated at a time, then only the first one will be evaluated.

Wrong Code:

trigger sample on Account (after insert) {  for (Account sample: Trigger. New) {             sample. Email =sample.Email__c;  } }

Modified Code:

trigger sample on Account (after insert) {  List<Account> Acclis = [SELECT Id,Name,Email,Email__C FROM Account WHERE Id IN: Trigger.newMap.keySet()];  for (Account Acc: Acclist){  Acc.Email = Acc.Email__c;  }Update Acclist;}

16.Required Field Missing:

Reason: In DML operation, we have missed the required field for the sObject.

Code: trigger Acc on Account (after insert) {  List<Contact> ListCont =New List<Contact>();  for(Account acnt : Trigger.New)  {  for(integer i=0;i<3;i++)  {  Contact Cont=new Contact();  cont.accountid=acnt.id;  ListCont.add(cont);  }  }  insert ListCont;      }

Modified Code:

 trigger Acc on Account (after insert) {  List<Contact> ListCont =New List<Contact>();  for(Account acnt : Trigger.New)  {  for(integer i=0;i<3;i++)  {  Contact Cont=new Contact();  Cont.Lastname = acnt.Name+’Sample’;   //This is the required field in Contact  cont.accountid=acnt.id;  ListCont.add(cont);  }  }  insert ListCont;      }  

17. Error: Compile Error: Invalid foreign key relationship: Account.Site at line 15 column 12:

Reason: While assigning a field value,  the Syntax should be SobjectName.FieldName or SObjectName.method()

Sample Code (Error)  trigger sample on Account(before insert, before update){  integer i = 0;   Map<String, Account> accountMap = new Map<String, Account>{};  for (Account acct : System.Trigger.new)  accountMap.put(acct.Name,acct);  for (Account oldAccount: [SELECT Id, Name,Site FROM Account WHERE Name IN:accountMap.KeySet()]){  Account newAccount = accountMap.get(oldAccount.Name);  i = newAccount.Site.length;  }  }  Modified Code:  trigger sample on Account (before insert, before update){  integer i = 0;   Map<String, Account> accountMap = new Map<String, Account>{};  for (Account acct : System.Trigger.new)  accountMap.put(acct.Name,acct);  for (Account oldAccount : [SELECT Id,Name,Site FROM Account WHERE NameIN :accountMap.KeySet()]) {  Account newAccount = accountMap.get(oldAccount.Name);  i = newAccount.Site.length();  }}  

18.System.security. NoAccessException: Update access denied for RecordType controller action methods may not execute:

Reason: This error means that the profile that executes the apex code has no permission to create the sObject.
Resolution: Check whether do you have access to the apex code, or to modify your profile
– change the first line of apex code from “public with sharing…” to “public without sharing…”.
or
- Add create permission to your profile (setup / manage users / profiles / your profile / check create checkbox in account object)

19. System.SObjectException: DML statement cannot operate on trigger. New or trigger. Old: Trigger.extractnumericvalues:

Reason: We cannot perform DML operation in before insert/before update in same record. Also, refer the Order of Execution.

Sample Code:

trigger extractnumericvalues on Account (before insert) { list<account> acList = new list<account>(); Matcher matcher; Pattern pat; for(account acc : trigger. New) { if(acc.AccountNumber != null) { pat = Pattern.compile('[0-9]'); matcher = pat. matcher(acc. Account Number); Boolean matches = matcher.find(); acc.Copy_Me__c = matcher.group(); acList.add(acc); } } insert acList;// Error will flow here because we cannot do dml for the same record. }

20.Error: Invalid Data Review all error messages below to correct your data. Apex trigger trigger task caused an unexpected exception, contact your administrator: trigger task: data changed by trigger for field Pick Val: bad value for restricted picklist field: Val10:

Reason: In trigger, when we try to insert new values into the picklist rather than using the existing values in the picklist, this error will fire during insertion.

Resolution:

Solution 1:  To accept the new values apart from the existing picklist values: Goto View Fields–>Corresponding Picklist–>Edit–>Picklist Options–>uncheck the “Restrict picklist to the values defined in the value set”.

Solution 2: Adding a necessary picklist value to the existing picklist.

References

1.Help page Document

2.Developer.Salesforce

SFDC common errors相关推荐

  1. org.apache.kafka.common.errors.TimeoutException: Topic not present in metadata 解决方法

    [README] 本文po出了 topic not present in metadata 的解决方法: 很多博文说是 因为  jackson-databind 没有引入,但是我重新引入后,还是没有解 ...

  2. php common errors

    编译安装PHP 时遇到问题解决方法. 环境:centos X64 最小化安装 php版本:php-5.4.3 安装前.先安装些软件和库文件 yum install -y gcc gcc-c++  ma ...

  3. kafka消费报错:org.apache.kafka.common.errors.WakeupException: null

    文章目录 1. 背景 1. 背景 我在测试类中写一个kafka消费者的线程,大概结构如下 @Testpublic void startMeteorTask() {thread.run(){

  4. 开放神经网络交换(ONNX)工具

    开放神经网络交换(ONNX)工具 开放神经网络交换(ONNX)是一个开放的生态系统,它使人工智能开发人员能够在项目发展过程中选择正确的工具.ONNX为人工智能模型提供了一种开源格式,包括深度学习和传统 ...

  5. kafka 异步发送阻塞_Kafka学习一

    一.github下载kafka的源码 可以看到kafka的源码开源社区是非常活跃的. 二.搭建kafka环境 构建kafka环境,首先需要安装Scala和gradle,再安装的scala插件需要和你的 ...

  6. 编写文档_如何通过编写优质文档来使自己的未来快乐

    编写文档 by Gabriele Cimato 加布里埃莱·西马托(Gabriele Cimato) 如何通过编写优质文档来使自己的未来快乐 (How to make your future self ...

  7. babel6 babel7_当您已经准备好Babel时设置Flow

    babel6 babel7 by Jamie Kyle 杰米·凯尔(Jamie Kyle) 当您已经准备好Babel时设置Flow (Setting up Flow when you've alrea ...

  8. javascript优缺点_为什么要在JavaScript中使用静态类型? 优缺点

    javascript优缺点 by Preethi Kasireddy 通过Preethi Kasireddy 为什么要在JavaScript中使用静态类型? 优缺点 (Why use static t ...

  9. 对象冒充_使用您的精神探照灯进行冒充冒名顶替综合症

    对象冒充 by Jaime J. Rios 由Jaime J. Rios "Stop that imposter! Seize them!" "停止冒名顶替者! 抓住他们 ...

  10. 深入理解Kafka Connect:转换器和序列化

    AI前线导读:Kafka Connect是一个简单但功能强大的工具,可用于Kafka和其他系统之间的集成.人们对Kafka Connect最常见的误解之一是它的转换器.这篇文章将告诉我们如何正确地使用 ...

最新文章

  1. mybaits错误解决:There is no getter for property named 'parentId ' in class 'java.lang.String'
  2. 各浏览器对document.getElementById等方法的实现差异
  3. Visual Studio常用快捷键(非常实用)
  4. linux下导入、导出mysql数据库命令 下载文件到本地
  5. 久谦咨询python笔试题目_【久谦咨询面试|面试题】-看准网
  6. Android与Libgdx环境配置
  7. 3部世界顶级宇宙纪录片,献给对宇宙万物充满好奇的你~
  8. 天气情况图像分类练习赛 第三阶段(赛中感)
  9. 测试Spring Boot有条件的合理方式
  10. python计算PR曲线sklearn.metrics.precision_recall_curve
  11. svg标签的CSS3动画特效 - 经典特效
  12. 理解CapsuleNetwork2
  13. c 中html上传文件大小,IOS微信内置浏览器对html标签input type=file上传的文件大小size错误?...
  14. xml规范及xml解析
  15. sumo 仿真输出转trj文件 用于SSAM分析
  16. 《RFID技术与应用》试题库(含答案)
  17. fiddler软件抓包工具超详细配置方法
  18. java 无法加载dll_java中调用本地动态链接库(*.DLL)的两种方式详解和not found library、打包成jar,war包dll无法加载等等问题解决办法...
  19. JAVA Oracle插入大量数据优化
  20. Linux----putty下载安装教程

热门文章

  1. 【上海房价预测】代码实现——利用BP神经网络进行上海二手房价预测
  2. 不同型号阵列卡相关工具的使用简介
  3. Java多线程篇--原子包、阻塞队列和并行流
  4. 树莓派Pico开发版
  5. OpenGL ES EGL eglMakeCurrent
  6. 【Linux】深入解析Linux proc文件系统
  7. ios客户端学习-创建pch文件
  8. 【实验】实验课总结1 绘制简单电路图
  9. 英语单词辨析(同类单词)
  10. 输入某年某月某日,判断这一天是这一年的第几天?