2

I am building a Apex Rest Endpoint. I am receiving an "Attempt to de-reference a null object" on the following line:

cm.rsmEmailOpenCount__c += 1;

I dumped all of the Objects (Lead, Campaign and CampaignMember) and the Ids are all correct. The first two SELECTS in the class execute without error as response.message = 'CampaignMember with (Campaign,Lead) pair not found'. I've run out of ideas on how to debug this one.

Here is the class:

@RestResource(urlMapping='/EmailOpens/*')
global with sharing class RsmEmailOpens {

  // inbound JSON payload is an array/List named "opens" of this type
  global class Item {
    public String cname;
    public String email;
  }

  // outbound response type
  global class Response {
    public String message;
    public Integer updates;
    public String cname;
    public String email;
    public String exception_msg;
  }

  @HttpPatch
  global static Response RsmIncrementEmailOpens(List<Item> opens) {
    Response response = new Response();
    Integer updates = 0;
    String error_msg = '';

    for (Item i : opens) {  
      try {
        error_msg = 'Lead.Email not found';  // msg if the following fails
        Lead lead = [SELECT Id FROM Lead WHERE Email =: i.email];

        error_msg = 'Lead.Email found; Campaign.Name not found';
        Campaign campaign = [SELECT Id FROM Campaign WHERE Name =: i.cname];

        error_msg = 'Lead.Email & Campaign.Name found; CampaignMember with (Campaign,Lead) pair not found';
        CampaignMember cm = [SELECT rsmEmailOpenCount__c FROM CampaignMember 
          WHERE CampaignId =: campaign.Id AND LeadId =: lead.Id];
        cm.rsmEmailOpenCount__c += 1;
        update cm;

      } catch(Exception e) {
          response.message = error_msg;
          response.updates = updates;
          response.cname = i.cname;
          response.email = i.email;
          response.exception_msg = e.getMessage();         
          return response;
      }
      updates++;
    }

    response.message = 'Successful';
    response.updates = updates;  
    response.cname = Null;
    response.email = Null;
    response.exception_msg = Null;
    return response;
  } 
}

Thank you for reviewing this.

1 Answer 1

2

You don't know when you make your query if the field has any value specified. If cm.rsmEmailOpenCount__c is null, then trying to increment it will attempt to de-reference a null value, and give you the error you observed. Instead, check if it is null. One way to do so is a ternary operator:

cm.rsmEmailOpenCount__c = (cm.rsmEmailOpenCount__c == null) ?
    1 : 1 + cm.rsmEmailOpenCount;

Or you could just set it to zero in the null case.

if (cm.rsmEmailOpenCount__c == null)
    cm.rsmEmailOpenCount__c = 0;
cm.rsmEmailOpenCount++;
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .