[SalesForce] System.DmlException: Insert failed. First exception on row 0; first error:

I have the error message above, but I am not sure, what else to take care of.
My Code is the following and the error is in a test class

My Code:

trigger AddAccEuroAISNo on Task (before insert, before update) {
for (Task a : trigger.new){ 
          if(Task.WhoId != null){
        String WhoIdString = String.valueof(a.WhoId);
            if (WhoIdString.substring(0,3) == '003'){
            Contact parent = [SELECT AccountId, Account.Name, Name, EuroAIS_Customer_Number__c  FROM Contact WHERE ID = :a.WhoId ];
            if(parent.AccountId  != null){
            a.Account__c = parent.Account.Name;
            a.EuroAISCustomerId__c = parent.EuroAIS_Customer_Number__c;
            a.Contact__c = parent.Name;
            }}}}}

The Error Message:

Test_MergeCasesController.caseMergeTestMethod(), Details: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AddAccEuroAISNo: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.AddAccEuroAISNo: line 5, column 1: [] Class.MergeCasesController.mergeCases: line 181, column 1 Class.Test_MergeCasesController.caseMergeTestMethod: line 48, column 1

Thanks a lot in advance for any help

Best Answer

The problem is that you are not setting a value for the WhoId on the Task that you are inserting.

What is essentially happening is this:

Task a = new Task();
String WhoIdString = String.valueof(a.WhoId);
system.debug(WhoIdString);
system.debug(WhoIdString.substring(0,3) == '003');

In this line of your code:

if(Task.WhoId != null){    

it looks like you are attempting to check for null values, if you change it to:

if(a.WhoId != null){

you will not get the error message, but your test will also not cover the code inside the if block.

Related Topic