0

I have created a custom Exception class

public class StatusException extends Exception{};

when using it to throw an error it's throwing a null pointer exception too.

public class ContainerSync2 {
    public virtual class BaseException extends Exception {}
    
    public static Integer noOfRecordsProcessed=0;
    
    @InvocableMethod(label='Do Sync' description='To Start the Campaign Container Sync.')
    public static void doSync(){
        ContainerSync2.sync();
    }
    
    public static void sync(){
        List<String> errors=new List<String>();
        String errorResponse='';
        try{
            List<Campaign> campaignsToCreate=new List<Campaign>();
            String recordTypeId=Schema.SObjectType.Campaign.getRecordTypeInfosByName().get('Status IO Campaign').getRecordTypeId();
            List<Campaign> campaignList=[SELECT Id, Name, Status_IO_Component_Ids__c, Status_IO_Id__c, Type FROM Campaign WHERE Status_IO_Id__c != null];
            Map<String,Campaign> statusIoIdMAp=new Map<String,Campaign>();
            for(Campaign cmp:campaignList){
                statusIoIdMAp.put(cmp.Status_IO_Id__c,cmp);    
            }
        
            Http http=new Http();
            HttpRequest req=new HttpRequest();
            req.setEndpoint(myEndPoint);
            req.setHeader('Content-Type', 'application/json');
            req.setMethod('GET');
            req.setHeader('x-api-id', API_Id);
            req.setHeader('x-api-key', API_key);
         
            HttpResponse res=http.send(req);
            if(res.getStatus()=='OK'){
                //API successfull
                String apiResponse=res.getBody();
                apiResponse=apiResponse.replaceAll('_id', 'id');
                StatusIOjson obj=StatusIOjson.parse(apiResponse);
                system.debug(obj);
                if(obj.status.error=='yes') {
                    throw new BaseException('Sync Failed.');
                }
                noOfRecordsProcessed=obj.result.size();
                for(StatusIOjson.cls_result tmp:obj.result){
                    Campaign currentCampaign=statusIoIdMAp.get(tmp.id);
                    String addedContainerIds='';
                    for(StatusIOjson.cls_containers container:tmp.containers){
                        addedContainerIds=addedContainerIds+container.id+',';
                    }
                    addedContainerIds = addedContainerIds.removeEnd(',');
                    if(currentCampaign==null){
                        Campaign newCampaignToCreate=new Campaign();
                        newCampaignToCreate.Name=tmp.name;
                        newCampaignToCreate.Status_IO_Id__c=tmp.id;
                         newCampaignToCreate.Status_IO_Component_Ids__c=addedContainerIds;
                        newCampaignToCreate.Type='Status IO';
                        newCampaignToCreate.RecordTypeId=recordTypeId;
                        campaignsToCreate.add(newCampaignToCreate);
                    }else{
                        currentCampaign.Name=tmp.name;
                         currentCampaign.Status_IO_Component_Ids__c=addedContainerIds;
                    }
                }
                     
                //insert and update.
                insert campaignsToCreate;
                update statusIoIdMAp.values();
                     
            }/*else{
                //API failed.
                errorResponse=res.getBody();
            }  */ 
                 
        }catch(Exception e){
            errors.add(e.getMessage());
            System.debug(e.getCause());
            System.debug(e.getLineNumber());
            System.debug(e.getMessage());
        }finally{
            //use errors and send the email.
            List<Messaging.SingleEmailMessage> emailList = new List<Messaging.SingleEmailMessage>();
            List<String> address = new List<String>{'mridul.kapil@test.com'};
            
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setToAddresses(address);
            emailList.add(mail);
            if(errors.size()==0){
                mail.setSubject('Container Campaign Sync Successful');
                mail.setHtmlBody('Hi, <p>'+noOfRecordsProcessed+ ' Containers have been synced with Campaigns successfully.</p>');
            }else{
                mail.setSubject('Container Campaign Sync Failed');
                errors.remove(null);
                mail.setHtmlBody('Hi, <p> Containers sync failed. '+string.join(errors,',')+'</p>');
            }
        
            if(!emailList.isEmpty()){
                Messaging.sendEmail(emailList);
            }      
        }
    }
}
8
  • Hi Mridul, can you post the logs you are getting? (including what line the NPE is being thrown)
    – McCubo
    Jun 14 at 6:47
  • it's saying null in the cause at line number 40 which is " throw new BaseException('Sync Failed.'); " Jun 14 at 6:53
  • could you update your question including all code in the method you are calling? I just tested your code, as is in your question, and got no error. so it might be somewhere else.
    – McCubo
    Jun 14 at 7:01
  • added the whole class Jun 14 at 7:04
  • my guess is that obj.status.error is the one causing the NPE. add a System.debug(obj.status) right before the if statement and post its outcome.
    – McCubo
    Jun 14 at 7:23

1 Answer 1

0

removing errors.remove(null); worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.